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,
  ));
}),
相关推荐
小红星闪啊闪11 小时前
Flutter开发 -- 需要了解的Dart知识
flutter
小李A_Z12 小时前
[Flutter]介绍些flutter的弹窗
flutter
小李A_Z12 小时前
[Flutter]介绍写Flutetr的按钮
flutter
恋猫de小郭17 小时前
Flutter 官方 LLM 动态 UI 库 flutter_genui 发布,让 App UI 自己生成 UI
android·前端·flutter
tangweiguo0305198718 小时前
FlutterActivity vs FlutterFragmentActivity:全面对比与最佳实践
android·flutter
ITKEY_18 小时前
flutter日期选择国际化支持
开发语言·javascript·flutter
农夫三拳_有点甜18 小时前
Flutter SystemChrome 完整指南
flutter
葱段18 小时前
【Flutter】TextField 监听长按菜单粘贴点击事件
android·flutter·dart
2501_9197490319 小时前
flutter鸿蒙:使用flutter_local_notifications实现本地通知
flutter·华为·harmonyos
浮生若茶80881 天前
Flutter环境搭建全攻略之-Macos环境搭建
flutter·macos