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,
  ));
}),
相关推荐
nc_kai3 小时前
Flutter 之 每日翻译 PreferredSizeWidget
java·前端·flutter
littlegnal4 小时前
Flutter Add-to-app profiling
flutter
0wioiw010 小时前
Flutter基础(FFI)
flutter
Georgewu9 天前
【HarmonyOS 5】鸿蒙跨平台开发方案详解(一)
flutter·harmonyos
爱吃鱼的锅包肉10 天前
Flutter开发中记录一个非常好用的图片缓存清理的插件
flutter
张风捷特烈10 天前
每日一题 Flutter#13 | build 回调的 BuildContext 是什么
android·flutter·面试
恋猫de小郭10 天前
Flutter 又双叒叕可以在 iOS 26 的真机上 hotload 运行了,来看看又是什么黑科技
android·前端·flutter
QC七哥11 天前
跨平台开发flutter初体验
android·flutter·安卓·桌面开发
小喷友11 天前
Flutter 从入门到精通(水)
前端·flutter·app