Flutter开发圈Flutter

Flutter 拍照及相册图片选择功能实现

2020-06-24  本文已影响0人  墩儿

第三方插件支持

  1. camera
    支持自定义相机
  2. image_picker
    支持相册图片选择及拍照功能

image_picker

  1. 安装
    pubspec.yaml文件中新增依赖
dependencies:
 ...
 image_picker: ”0.6.0+8“

不确定版本可以写成image_picker: any下载成功后查看pubspec.lock文件获取明确版本号替换pubspec.yaml文件内版本号,及时替换防止依赖版本号不明确造成不必要的报错

  1. 设置ios权限
    找到Info.plist文件 项目根目录/ios/Runner/Info.plist
    添加以下keys
  1. 设置android权限
  1. 使用(旧API) (关键代码截取)
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

class UploadImage extends StatefulWidget {
  UploadImage({
    Key key,
  }) : super(key: key);

  @override
  _UploadImageState createState() => _UploadImageState();
}

class _UploadImageState extends State<UploadImage> {
  File _image;

  Future getImage() async {
    File image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (image != null) {
      setState(() {
        _image = File(image.path);
      });
    }
  }
  
  Future getLocalImage() async {
    File image = await ImagePicker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        _image = File(image.path);
      });
    }
  }
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Row(children: <Widget>[
           Expanded(
              child: RaisedButton(
                color: Colors.white,
                elevation: 0.0,
                padding: EdgeInsets.symmetric(vertical: 14.0, horizontal: 0),
                textColor: Color(0xFF1E4C8B),
                onPressed: getImage,
                child: new Text('拍照'),
              ),
            )
          ]),
          Divider(
            color: Color(0xFFE1E6EE),
            height: 1.0,
          ),
          Row(children: <Widget>[
            Expanded(
              child: RaisedButton(
                color: Colors.white,
                elevation: 0.0,
                padding: EdgeInsets.symmetric(vertical: 14.0, horizontal: 0),
                textColor: Color(0xFF1E4C8B),
                onPressed: getLocalImage,
                child: new Text('从相册选择'),
              ),
            )
         ]),
}
  1. 使用(新api 0.6.7)
  final _picker = ImagePicker();
  File _image;

  Future getImage() async {
    PickedFile image = await _picker.getImage(source: ImageSource.camera);
    if (image != null) {
      setState(() {
        _image = File(image.path);
      });
    }
  }
  
  Future getLocalImage() async {
    PickedFile image = await _picker.getImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        _image = File(image.path);
      });
    }
  }
上一篇下一篇

猜你喜欢

热点阅读