flutter 仿微信朋友圈发布图片

控件类,
里面放了很多自己写的一些组件,所以有很多相机用不到的引用,
但为了防止误删一些引用,所有的都没有删除,如果拿去用,灰色的可以直接删掉即可,
另外也可以传网络图片进去显示,格式为:

    PhotoFrame(imagesShow:_imagesShow);
    _imagesShow = [
			{id: 60, image: https://www.tricklen.com/publicImage/1bed62c0e9e7406795317f1b16e94632.jpg},
			 {id: 61, image: https://www.tricklen.com/publicImage/ed179d808682455e9cf8b8f0f9d40f08.jpg},
			  {id: 62, image: https://www.tricklen.com/publicImage/4015cf30afd94e60a3d3a5b2bd562827.jpg},
			   {id: 137, image: https://www.tricklen.com/publicImage/3046cc0f8d8746e7a0f3c70cb7add240.jpg},
			    {id: 138, image: https://www.tricklen.com/publicImage/5a668a7baae941a6ac826978ddbdf84e.jpg}
	];

其中,id为网图的id,是为了删除识别的需要


import 'package:flutter/material.dart';
import 'dart:math' as math;
import 'package:redenvelope/pages/extendBlackList/blackLiatDetails.dart';
import 'package:redenvelope/pages/extendBlackList/blackLiatDetails1.dart';
import 'package:redenvelope/constant/colors.dart';
import 'package:redenvelope/widget/UserImg.dart';
import 'package:fluttertoast/fluttertoast.dart'; //弹出框库
import 'package:image_picker/image_picker.dart'; //调用相机 相册
import 'package:dio/dio.dart';
import 'dart:io';
import 'package:photo/photo.dart'; //调用photo库
import 'package:photo_manager/photo_manager.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart'; //图片压缩
import 'dart:async';
import 'package:redenvelope/constant/App.dart';
import 'package:redenvelope/widget/UserImg.dart';
import 'package:redenvelope/pages/extendBlackList/domeData.dart';

// 相机组件
class PhotoFrame extends StatefulWidget{
  var imagesShow;
  PhotoFrame({this.imagesShow});
  @override
  State createState() {
    print("---------------图片是否传递---------------------");
    print(imagesShow);
    return new PhotoFrameState();
  }
}

class PhotoFrameState extends State with WidgetsBindingObserver {

  List _imageShow = [];

  // 获取的需要显示的数组
  List _imageUrlShow = [];

  var item; //数据封装

  Widget addImage;

  int index = 1;
  List imageUrl = []; //存放偶像头像地址的数组

  File _image; //当前图片
  List images = []; //记录所有图片
  List ConList = []; //显示复数图片的数组
  List _rq = []; //FormData内传递的值


  // 单张相机取图片
  Future getImage() async {

    var image = await ImagePicker.pickImage(source: ImageSource.camera); //相机
    _image = image;

    print(_image);
    images.add(_image);
    ff();


  }

  // 多张连选取图
  void _pickImage() async {

    List imgList = await PhotoPicker.pickAsset(
      //需要BuildContext
      context: context,

      ///以下是可选参数。
      themeColor: AppColors.colorPrimary,
      //标题颜色和底部颜色
      padding: 1.0,
      //项目填充
      dividerColor: Colors.grey,
      //分隔线颜色
      disableColor: Colors.grey.shade300,
      //复选框禁用颜色
      itemRadio: 0.88,
      //内容项目radio
      maxSelected: 8 - images.length -_imageUrlShow.length,
      //最大选择器图像计数
      provider: I18nProvider.chinese,
      //提供者:I18nProvider.chinese,
      // i18n提供者,默认为中文。 ,您可以自定义I18nProvider或使用ENProvider()
      rowCount: 3,
      //项目行数
      textColor: Colors.white,
      //文字颜色
      thumbSize: 150,
      //预览拇指大小,默认为64
      sortDelegate: SortDelegate.common,
      //默认是常见的,或者您可以自定义委托来对图库进行排序
      checkBoxBuilderDelegate: DefaultCheckBoxBuilderDelegate(
        activeColor: Colors.white,
        unselectedColor: Colors.white,
      ),
      //默认为DefaultCheckBoxBuilderDelegate,或者您创建自定义委托以创建复选框

      //loadingDelegate: this,
      //如果你想构建自定义加载小部件,请扩展LoadingDelegate,[参见example / lib / main.dart]

      badgeDelegate: const DurationBadgeDelegate(),
    );

    //List r = [];//路径
    for (var e in imgList) {
      _image = await e.file;
      //r.add(_image.absolute.path);//获取路径

      print(_image);
      images.add(_image);
    }

    ff();


  }

  // 处理图片
  void ff() {

    if (ConList.length > 1) {
      ConList.removeRange(1, ConList.length);
    }
    // 先读取传过来的图片,并显示
    if(_imageUrlShow.length!=0){
      for (var i = 0; i < _imageUrlShow.length; i++) {
        ConList.add(
          new Stack(
            alignment: const FractionalOffset(1.30, -0.3),
            children: [
              Container(
                height: 95,
                width: 95,
                child: Image.network(_imageUrlShow[i]["image"], fit: BoxFit.cover),
              ),
              IconButton(

                iconSize: 20,
                icon: Container(

                  child: Icon(Icons.clear,color: Colors.black,),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10.0), //10像素圆角

                  ),
                ),
                onPressed: () {
                  setState(() {
                    print("--------------------是否传递图片过来过---------------------------");
                    print(_imageUrlShow[i]["id"].toString());
                    print(ConList);
                    print(_imageUrlShow);

                    // 添加删除图片的id
                    SaveData.imagesRemoveId =
                        SaveData.imagesRemoveId +_imageUrlShow[i]["id"].toString()+"|";

                    //删除数组中存储的图片地址
                    var x = _imageUrlShow.remove(_imageUrlShow[i]);


                    print(x);
                    //删除组件
                    ConList.remove(ConList[i + 1]);

                    ff();
                  });
                },
              ),
            ],
          ),
        );
      }
    }


    // 在读取本地图片,并显示
    if(images.length!=0){
      for (var i = 0; i < images.length; i++) {
        ConList.add(
          new Stack(
            alignment: const FractionalOffset(1.30, -0.3),
            children: [
              Container(
                height: 95,
                width: 95,
                child: Image.file(images[i], fit: BoxFit.cover),
              ),
              IconButton(
                color: Colors.grey[350],
                iconSize: 20,
                icon: Container(

                  child: Icon(Icons.clear,color: Colors.black,),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10.0), //10像素圆角

                  ),
                ),
                onPressed: () {
                  setState(() {
                    //删除当前图片
                    _image = null;
                    //删除数组中存储的图片地址
                    var x = images.remove(images[i]);

                    print(x);
                    //删除组件
                    ConList.remove(ConList[i + 1]);
                    print(ConList);
                    ff();
                  });
                },
              ),
            ],
          ),
        );
      }
      _saveDate();
    }


    setState(() {});
  }

  // 封装数据
  Future _saveDate() async {

    _rq.clear();

    //压缩图片并封装
    for (var i = 0, len = images.length; i < len; i++) {
      File file = images[i];

      file = await FlutterImageCompress.compressAndGetFile(
        file.absolute.path,
        Directory.systemTemp.path + '/head' + i.toString() + '.jpg',
        minWidth: 1920,
        minHeight: 1080,
        quality: 60,
      );

      _rq.add(new UploadFileInfo(
          file, App.userid.toString() + i.toString() + ".jpg"));
    }

    SaveData.imagesListFlie   = images;
    SaveData.imagesList   = _rq;

    print("图片文件数组长度"+SaveData.imagesListFlie.length.toString());
    print("图片上传数据流数组长度"+SaveData.imagesList.length.toString());

    return true;
  }

  @override
  void initState() {
    super.initState();
    _imageUrlShow = widget.imagesShow==null?
    []:
    widget.imagesShow;

    ConList.add(Container(
      color: Colors.grey[200],
      height: 95,
      width: 95,
      child: FlatButton(
          onPressed: () {
            //弹出底部弹窗
            showModalBottomSheet(
                context: context,
                builder: (BuildContext context) {
                  return Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        decoration: BoxDecoration(
                          //背景装饰

                          borderRadius: BorderRadius.circular(5.0),
                        ),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            ListTile(
                              title: Center(
                                child: Center(
                                  child: Text(
                                    '请选择',
                                    style: TextStyle(color: Colors.black26,fontFamily:'appIconFonts'),
                                  ),
                                ),
                              ),
                            ),
                            Divider2(),
                            ListTile(
                              title: Center(
                                child: Text("拍照",style: TextStyle(fontFamily:'appIconFonts'),),
                              ),
                              onTap: () {
                                //调用相机
                                Navigator.of(context).pop();
                                images.length + _imageUrlShow.length < 8
                                    ? getImage()
                                    : Fluttertoast.showToast(
                                    msg: "图片的数量不能超过8张",
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.CENTER,
                                    timeInSecForIos: 1,
                                    backgroundColor: Colors.black12,
                                    textColor: Colors.black,
                                    fontSize: 16.0);
                              },
                            ),
                            Divider2(),
                            ListTile(
                              title: Center(
                                child: Text("从本地相册选择",style: TextStyle(fontFamily:'appIconFonts'),),
                              ),
                              onTap: () {
                                Navigator.of(context).pop();
                                //读取相册
                                images.length + _imageUrlShow.length < 8
                                    ? _pickImage()
                                    : Fluttertoast.showToast(
                                    msg: "图片的数量不能超过8张",
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.CENTER,
                                    timeInSecForIos: 1,
                                    backgroundColor: Colors.black12,
                                    textColor: Colors.black,
                                    fontSize: 16.0);
                              },
                            ),
                          ],
                        ),
                      ),
                      Container(
                        height: 10,
                        color: Colors.black26,
                      ),
                      ListTile(
                        title: Center(
                          child: Text(
                            "取消",
                            style: TextStyle(
                                fontWeight: FontWeight.w600,fontFamily:'appIconFonts'
                            ),
                            textScaleFactor: 1.0,
                          ),
                        ),
                      ),
                    ],
                  );
                });
          },
          child: Icon(
            Icons.add_a_photo,
            color: Colors.black26,
          )),
    ));

    ff();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (App.wangLuoZhaugnTai == 1) {
      return Center(
        child: Text('网络错误,无法执行...',style: TextStyle(fontFamily:'appIconFonts'),),
      );
    }


    print(ConList);


    return Container(
//
        padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
        margin: EdgeInsets.only(left: 10.0, right: 10.0, bottom: 0.0),
        child: Container(
          child: Wrap(
            spacing: 8.0, // 主轴(水平)方向间距
            runSpacing: 4.0, // 纵轴(垂直)方向间距
            children: ConList,
          ),
        ));
  }
}

需要几个插件
image_picker
flutter_image_compress
photo
flutter 仿微信朋友圈发布图片_第1张图片
在这里插入图片描述
这个是压缩图片的,非必须,但是如果不用,就可以直接注释掉关于这个插件的调用

调用很简单,一句话,如果不用显示上次图片,不用传递参数

	PhotoFrame();

另外需要一个存储类,用来存储选中的图片

// 存储选择图片
class SaveData {

  // 存储图片文件
  static  List imagesListFlie=[] ;

  // 存储图片字节码
  static  List imagesList = [];

// 需要删除的图片的id,这些图片为上次上传的图片
  static  String imagesRemoveId = '';

  // 当前坐标
  static double X;
  static double Y;

  // 清除缓存,初始化数据
  static void  clearListFlie(){
    SaveData.imagesListFlie.clear();
    SaveData.imagesList.clear();
    SaveData.imagesRemoveId = "";
  }


}

clearListFlie方法用于重复调用此控件的时候防止上次的数据残留,可以写在每次调用控件的之前

你可能感兴趣的:(flutter)