Flutter photo_view 图片预览缩放 使用优化

photo_view 是一个处理图片缩放以及多图滑动查看的插件,在实际开发中像圈子,社交类型的APP,都会用到多图的查看以及缩放。

在这里我对photo_view进行一个再封装,在项目中可以直接使用,代码如下:

首先要在pubspec.yaml中添加:
dependencies:
photo_view: ^0.4.2

class PreviewImagesWidget extends StatefulWidget {
  ///图片Lst
  final List imageList;

  ///初始展示页数。默认0
  int initialPage;

  ///选中的页的点的颜色
  Color checkedColor;

  ///未选中的页的点的颜色
  Color uncheckedColor;

  PreviewImagesWidget(this.imageList,
      {this.initialPage = 0,
      this.checkedColor = Colors.white,
      this.uncheckedColor = Colors.grey});

  @override
  _PreviewImagesWidgetState createState() =>
      _PreviewImagesWidgetState(initialPage: initialPage);
}

class _PreviewImagesWidgetState extends State {
  PageController pageController;
  int nowPosition;
  int initialPage;
  List dotWidgets;

  _PreviewImagesWidgetState({this.initialPage = 0});

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    nowPosition = initialPage;
    pageController = PageController(initialPage: initialPage);
    _initData();
  }

  void _initData() {
    dotWidgets = [];
    if (widget.imageList.length > 1) {
      for (int i = 0; i < widget.imageList.length; i++) {
        dotWidgets.add(_buildDots(i));
      }
    }
  }

  Widget _buildDots(int index) => Container(
        margin: EdgeInsets.all(5),
        child: ClipOval(
          child: Container(
            color: index == nowPosition
                ? widget.checkedColor
                : widget.uncheckedColor,
            width: 5.0,
            height: 5.0,
          ),
        ),
      );

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => Navigator.of(context).pop(),
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: [
          PhotoViewGallery.builder(
            onPageChanged: (index) {
              setState(() {
                nowPosition = index;
                _initData();
              });
            },
            scrollPhysics: const BouncingScrollPhysics(),
            builder: (BuildContext context, int index) {
              return PhotoViewGalleryPageOptions(
                imageProvider: NetworkImage(widget.imageList[index]),
              );
            },
            itemCount: widget.imageList.length,
            pageController: pageController,
          ),
          Container(
            margin: EdgeInsets.only(bottom: 10),
            child: Wrap(
              children: dotWidgets,
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    pageController.dispose();
  }
}

具体使用方式:

Navigator.of(ctx.context).push(PageRouteBuilder(
        pageBuilder: (c, a, s) => PreviewImagesWidget(urls,initialPage: 1,)));

你可能感兴趣的:(flutter)