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,
  ));
}),
相关推荐
小a杰.5 分钟前
Flutter 与 AI 深度集成指南:从基础实现到高级应用
人工智能·flutter
程序员老刘7 小时前
跨平台开发地图:客户端技术选型指南 | 2025年12月
flutter·客户端
一名普通的程序员7 小时前
使用 Flutter Pay 插件实现 Apple Pay 和 Google Pay 的完整指南
flutter
麦客奥德彪8 小时前
Flutter riverpod 对应Android开发概念理解
flutter
tangweiguo030519879 小时前
Kotlin vs Dart vs Swift:语法对比全解
flutter
feelingHy9 小时前
GetX 状态管理实践
flutter
tangweiguo0305198710 小时前
Flutter多品牌应用架构实战:从配置驱动到编译部署的完整解决方案
flutter
Bryce李小白11 小时前
FlutterBoost适配Flutter3.38.4版本生成补丁包
flutter
tangweiguo0305198712 小时前
Flutter Packages 设计与实践:构建可维护的模块化应用
flutter
小a杰.12 小时前
Flutter 的编译技术核心
flutter