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,
  ));
}),
相关推荐
ITfeib4 小时前
Flutter基础
flutter
RaidenLiu7 小时前
RepaintBoundary是什么?怎么用?
flutter
淹没9 小时前
🚀 告别复杂的HTTP模拟!HttpHook让Dart应用测试变得超简单
android·flutter·dart
吴Wu涛涛涛涛涛Tao14 小时前
Flutter 个人主页实践笔记
flutter
愿天深海14 小时前
Flutter 提取图像主色调 ColorScheme.fromImageProvider
android·前端·flutter
梦想改变生活1 天前
《Flutter篇第一章》基于GetX 和 Binding、Dio 实现的 Flutter UI 架构
flutter·ui·架构
耳東陈2 天前
[重磅发布] Flutter Chen Generator 必备脚本工具
flutter
亿刀2 天前
【学习VPN之路】NET技术
android·flutter
浅蓝色2 天前
Flutter平台判断问题,并适配鸿蒙
flutter