1- 导入包 具体版本请前往pub.dev查看
# 图片预览 photo_view: ^0.13.0
2- 路由动画组件
import 'package:flutter/cupertino.dart'; /// 路由动画 class FadeRoute extends PageRouteBuilder { final Widget page; FadeRoute({this.page}) : super( pageBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) => page, transitionsBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) => FadeTransition( opacity: animation, child: child, ), ); }
3- 真正实现大图查看
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:photo_view/photo_view.dart'; import 'package:photo_view/photo_view_gallery.dart'; class PhotoViewGalleryScreen extends StatefulWidget { List images = []; int index = 0; String heroTag; PageController controller; bool isFile = false; PhotoViewGalleryScreen( {Key key, @required this.images, this.index, this.controller, this.heroTag, this.isFile }) : super(key: key) { controller = PageController(initialPage: index); } @override _PhotoViewGalleryScreenState createState() => _PhotoViewGalleryScreenState(); } class _PhotoViewGalleryScreenState extends State<PhotoViewGalleryScreen> { int currentIndex = 0; @override void initState() { super.initState(); currentIndex = widget.index; } @override Widget build(BuildContext context) { return Scaffold( body: Container( decoration: BoxDecoration( color: Colors.black, ), constraints: BoxConstraints.expand( height: MediaQuery.of(context).size.height, ), child: Stack( children: <Widget>[ Container( child: PhotoViewGallery.builder( scrollPhysics: const BouncingScrollPhysics(), builder: (BuildContext context, int index) { return PhotoViewGalleryPageOptions( imageProvider: widget.isFile?FileImage(File(widget.images[index].path)):NetworkImage(widget.images[index]), heroAttributes: widget.heroTag.isNotEmpty ? PhotoViewHeroAttributes(tag: widget.heroTag) : null, ); }, itemCount: widget.images.length, backgroundDecoration: null, pageController: widget.controller, enableRotation: true, onPageChanged: (index) { setState(() { currentIndex = index; }); }, )), Positioned( top: MediaQuery.of(context).padding.top + 15, width: MediaQuery.of(context).size.width, child: Center( child: Text("${currentIndex + 1}/${widget.images.length}", style: TextStyle(color: Colors.white, fontSize: 16)), ), ), Positioned( right: 10, top: MediaQuery.of(context).padding.top, child: IconButton( icon: Icon( Icons.close, size: 30, color: Colors.white, ), onPressed: () { Navigator.of(context).pop(); }, ), ), ], ), ), ); } }
4- 代码中使用
在图片上添加GestureDetector ,在ontap中写入下列内容
Navigator.of(context).push(new FadeRoute( page: PhotoViewGalleryScreen( images: imgList, //传入图片list index: index, //传入当前点击的图片的index heroTag: '', isFile: false)));
以上便实现大图预览功能