import 'dart:io'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:photo_view/photo_view.dart'; import 'package:photo_view/photo_view_gallery.dart'; class GalleryPhotoViewWrapper extends StatefulWidget { final int initialIndex; final PageController pageController; /// 相册照片 final List? galleryItems; /// 网络图片 final List? netImgList; GalleryPhotoViewWrapper({ super.key, this.initialIndex = 0, this.galleryItems, this.netImgList, }) : pageController = PageController(initialPage: initialIndex); @override State createState() => _GalleryPhotoViewWrapperState(); } class _GalleryPhotoViewWrapperState extends State { late ValueNotifier indexVal = ValueNotifier(widget.initialIndex); PhotoViewGalleryPageOptions _buildItem(BuildContext context, int index) { return (widget.galleryItems ?? [] ).isNotEmpty ? PhotoViewGalleryPageOptions( imageProvider: FileImage(File(widget.galleryItems![index].path)) , initialScale: PhotoViewComputedScale.contained, minScale: PhotoViewComputedScale.contained * (0.5 + index / 10), maxScale: PhotoViewComputedScale.covered * 4.1, ) : PhotoViewGalleryPageOptions( imageProvider: CachedNetworkImageProvider(widget.netImgList![index]) , initialScale: PhotoViewComputedScale.contained, minScale: PhotoViewComputedScale.contained * (0.5 + index / 10), maxScale: PhotoViewComputedScale.covered * 4.1, ); } @override Widget build(BuildContext context) { return Scaffold( body: Container( decoration: const BoxDecoration( color: Colors.black, ), constraints: BoxConstraints.expand( height: MediaQuery.of(context).size.height, ), child: Stack( alignment: Alignment.bottomCenter, children: [ PhotoViewGallery.builder( scrollPhysics: const BouncingScrollPhysics(), builder: _buildItem, itemCount: widget.galleryItems?.length ?? widget.netImgList?.length, pageController: widget.pageController, onPageChanged: (index) { indexVal.value = index; }, ), Padding( padding: const EdgeInsets.only(bottom: 12), child: ValueListenableBuilder( valueListenable: indexVal, builder: (context, index, child) { return Text( "${index + 1}/${widget.galleryItems?.length ?? widget.netImgList?.length}", style: const TextStyle( color: Colors.white, fontSize: 18.0, ), ); }), ), Positioned( top: 28, left: 8, child: IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon( Icons.arrow_circle_left, color: Colors.white, size: 38, )), ), ], ), ), ); } }