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,
  ));
}),
相关推荐
fouryears_234179 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
LinXunFeng14 小时前
Flutter - 详情页 TabBar 与模块联动?秒了!
前端·flutter·开源
阅文作家助手开发团队_山神18 小时前
第三章: 解决Android iPad蓝牙键盘联想词UI不跟随光标问题
flutter
阅文作家助手开发团队_山神18 小时前
第四章:Flutter自定义Engine本地依赖与打包流程
前端·flutter
程序员老刘19 小时前
Flutter 3.35 更新要点解析
flutter·ai编程·客户端
阅文作家助手开发团队_山神20 小时前
第一章: Mac Flutter Engine开发准备工作
前端·flutter
EmmaGuo20151 天前
flutter3.7.12版本设置TextField的contextMenuBuilder的文字颜色
前端·flutter
鹏多多.1 天前
flutter-使用device_info_plus获取手机设备信息完整指南
android·前端·flutter·ios·数据分析·前端框架
来来走走1 天前
Flutter开发 网络请求
android·flutter
SoaringHeart2 天前
Flutter进阶:高内存任务的动态并发执行完美实现
前端·flutter