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,
  ));
}),
相关推荐
liulian091618 分钟前
Flutter for OpenHarmony 跨平台开发:BMI计算器功能实战指南
flutter·华为
xmdy58663 小时前
Flutter+开源鸿蒙实战|智安盾电商溯源平台Day1 项目搭建与整体方案拆解
flutter·开源·harmonyos
小白64029 小时前
AI辅助设计Flutter蓝牙自动连接系统
人工智能·flutter
xmdy58669 小时前
Flutter+开源鸿蒙实战|智联邻里Day6 引入GetX全局架构+升级版下拉刷新+Toast弹窗+网络状态监听
flutter·开源·harmonyos
xmdy586610 小时前
Flutter+开源鸿蒙实战|智联邻里Day5 闲置详情页+删除功能+下拉刷新+交互优化
flutter·开源·harmonyos
maaath10 小时前
【maaath】Flutter for OpenHarmony 媒体工具应用开发实战
flutter·华为·harmonyos
maaath11 小时前
【maaath】 Flutter for OpenHarmony 快捷工具箱应用实战开发
flutter·华为·harmonyos
maaath12 小时前
【maaath】Flutter for OpenHarmony 实战:茶叶茶艺应用开发详解
flutter·华为·harmonyos
maaath12 小时前
【maaath】Flutter for OpenHarmony 的手办展示应用开发实践
flutter·华为·harmonyos
jiejiejiejie_1 天前
Flutter for OpenHarmony 心情日记功能实战指南
flutter·华为