Flutter 拍照和上传封装(单张)

2021-03-25  本文已影响0人  景小帮

实现功能:拍照和选择相册,单张上传,自己封装了一个类,方便使用直接调用

注:多照片上传后期封装 发布

1、在pubspec.yaml 中添加插件

#单照片,使用相机拍摄和图库选择照片

image_picker: 0.6.7+22

2.封装相册和拍照

import 'dart:io';

import 'package:image_picker/image_picker.dart';

///

/// 图片上传封装(单张图片)

///

class PickImageResponse{

Listpaths; // 用于上传

  Listfiles; // 用于展示用的缩略图

  final ImagePickerpicker =ImagePicker();

  PickImageResponse({this.paths, this.files});

  /// 打开相机

  Future Function()openCamera = ()async {

    var image =await ImagePicker.pickImage(source: ImageSource.camera);

    if (image.path ==null)return PickImageResponse();

    return PickImageResponse(

        paths: [image.path],

        files: [File(image.path)]

    );

  };

  ///打开相册

  Future Function()openPhoto = ()async {

    var image =await ImagePicker.pickImage(source: ImageSource.gallery);

    if (image.path ==null)return PickImageResponse();

    return PickImageResponse(

        paths: [image.path],

        files: [File(image.path)]

    );

  };

}

调用方法,注:布局样式自己写

List<String> pathsList; // 用于上传

List<File> pathFiles; // 用于展示用的缩略图

PickImageResponse().openCamera().then((camera) => {

    setState(() {

        pathFiles = camera.files;

      })

});

PickImageResponse().openPhoto().then((photo) => {

    setState(() {

        pathFiles = photo.files;

      })

});

上一篇下一篇

猜你喜欢

热点阅读