Flutter:组件9、图片预览

js 复制代码
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:get/get.dart';

class ImagePreview extends StatelessWidget {
  final String? singleImage;
  final List<String>? imageList;
  final int initialIndex;

  const ImagePreview({
    super.key,
    this.singleImage,
    this.imageList,
    this.initialIndex = 0,
  });

  @override
  Widget build(BuildContext context) {
    // 如果提供了单张图片,转换为列表
    final List<String> images = singleImage != null 
        ? [singleImage!] 
        : imageList ?? [];

    if (images.isEmpty) return const SizedBox();

    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.close, color: Colors.white,size: 24,),
          onPressed: () => Get.back(),
        ),
      ),
      body: PhotoViewGallery.builder(
        itemCount: images.length,
        builder: (context, index) {
          return PhotoViewGalleryPageOptions(
            imageProvider: NetworkImage(images[index]),
            initialScale: PhotoViewComputedScale.contained,
            minScale: PhotoViewComputedScale.contained,
            maxScale: PhotoViewComputedScale.covered * 2,
          );
        },
        scrollPhysics: const BouncingScrollPhysics(),
        backgroundDecoration: const BoxDecoration(color: Colors.black),
        pageController: PageController(initialPage: initialIndex),
      ),
    );
  }
} 

使用方式:单张预览

js 复制代码
onTap(() {
  Get.to(() => ImagePreview(singleImage: '图片url'));
})

使用方式:多张预览

js 复制代码
List<String> img = ['图片url','图片url','图片url'];
for(var i = 0; i < (img.length ?? 0); i++)
ImgWidget(
  path: item.img?[i] ?? '',
  width: 170.w,
  height: 170.w,
  radius: 20.w,
).onTap(() {
  Get.to(() => ImagePreview(
    imageList: item.img,
    initialIndex: i,
  ));
}),
相关推荐
谢斯7 小时前
编译AppFlowy
flutter
灰灰勇闯IT9 小时前
Flutter×鸿蒙深度融合指南:从跨端适配到分布式能力落地(2025最新实战)
分布式·flutter·harmonyos
x.Jessica10 小时前
关于Flutter在Windows上开发的基本配置时遇到的问题及解决方法
windows·flutter
名字被你们想完了10 小时前
flutter 封装一个 tab
flutter
AiFlutter12 小时前
Flutter实现手电筒亮度修改
flutter
食品一少年14 小时前
【Day7-10】开源鸿蒙之Flutter 的自定义组件封装(1)
flutter·开源·harmonyos
勇气要爆发15 小时前
【第五阶段—高级特性和架构】第六章:自定义Widget开发指南
flutter
白茶三许19 小时前
【2025】Flutter 卡片组件封装与分页功能实现:实战指南
flutter·开源·openharmony
Bervin1213819 小时前
Flutter Android环境的搭建
android·flutter
fouryears_234171 天前
现代 Android 后台应用读取剪贴板最佳实践
android·前端·flutter·dart