赞
踩
引入插件,注:官方的功能很多,这里只是最简单的应用
photo_view: ^0.10.2///注:不同版本的方法可能不一样
直接上代码,有注释(PhotoPreview文件)
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:photo_view/photo_view_gallery.dart'; typedef PageChanged = void Function(int index); class PhotoPreview extends StatefulWidget { final List galleryItems; //图片列表 final int defaultImage; //默认第几张 final PageChanged pageChanged; //切换图片回调 final Axis direction; //图片查看方向 final Decoration decoration;//背景设计 PhotoPreview( {this.galleryItems, this.defaultImage = 1, this.pageChanged, this.direction = Axis.horizontal, this.decoration }) : assert(galleryItems != null); @override _PhotoPreviewState createState() => _PhotoPreviewState(); } class _PhotoPreviewState extends State<PhotoPreview> { int tempSelect; @override void initState() { // TODO: implement initState tempSelect=widget.defaultImage+1; } @override Widget build(BuildContext context) { return Material( child: Stack( children: [ Container( child: PhotoViewGallery.builder( scrollPhysics: const BouncingScrollPhysics(), builder: (BuildContext context, int index) { return PhotoViewGalleryPageOptions( imageProvider: NetworkImage(widget.galleryItems[index]), ); }, scrollDirection: widget.direction, itemCount: widget.galleryItems.length, backgroundDecoration: widget.decoration??BoxDecoration(color: Colors.white), pageController: PageController(initialPage: widget.defaultImage), onPageChanged: (index) =>setState(() { tempSelect=index+1; if( widget.pageChanged!=null) {widget.pageChanged(index);} }))), Positioned(///布局自己换 right: 20, top: 20, child: Text('$tempSelect/${widget.galleryItems.length}',style: TextStyle(color:Colors.black),), ) ], ), ); } }
使用例子
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:gzzoc/utils/photo_preview.dart'; class Test extends StatelessWidget { List list=[ 'https://goss.cfp.cn/creative/vcg/veer/800/new/VCG41N667607058.jpg', 'https://goss1.cfp.cn/creative/vcg/800/new/VCG41N1210205351.jpg', 'https://goss.cfp.cn/creative/vcg/800/new/VCG211241121526.jpg', ]; @override Widget build(BuildContext context) { return Material( child: Container( child: Center( child:ListView.builder( itemCount: list.length, scrollDirection:Axis.horizontal, itemBuilder:(context,index){ return Container( width: 140, height: 140, child: InkWell( onTap: (){ Navigator.push(context,MaterialPageRoute(builder:(_)=>PhotoPreview( galleryItems:list, defaultImage: index, ))); }, child: Image.network(list[index]), ), ); },) ) ), ); } }
效果图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。