在原生开发中,拍照及从图库选择图片是非常常见的需求,而且原生的图片选择第三方库也有很多并且很完善了。
Flutter也给我们提供了好用的图片选择插件,ios和Android都能用的 image_picker
Flutter拍照:
Flutter选择图片:
使用方法
一、在pubspec.yaml加入image_picker的依赖,版本号在github上找最新的即可。
如下:
dependencies: image_picker: ^0.6.2+1添加完依赖,在VSCODE,直接Ctrl+s保存,会自动get到本地。
二、IOS中要获取权限:
找到:<project root>/ios/Runner/Info.plist,添加下面代码,描述自己根据需求写即可:
<key>NSPhotoLibraryUsageDescription</key> <string>XXX需要获取相册权限</string> <key>NSCameraUsageDescription</key> <string>XXX需要获取相机权限</string> <key>NSMicrophoneUsageDescription</key> <string>XXX需要获取麦克风权限</string>三、导包
import 'package:image_picker/image_picker.dart';四、使用
拍照
var image = await ImagePicker.pickImage(source: ImageSource.camera);相册
var image = await ImagePicker.pickImage(source: ImageSource.gallery);五、完整代码:
import 'package:flutter/material.dart'; import 'dart:io'; //这个必须引入,因为用到了File import 'package:image_picker/image_picker.dart'; class ImagePickerWidget extends StatefulWidget { @override State<StatefulWidget> createState() { return _ImagePickerState(); } } class _ImagePickerState extends State<ImagePickerWidget> { File _imgPath; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("ImagePicker"), ), body: SingleChildScrollView( child: Column( children: <Widget>[ _ImageView(_imgPath), RaisedButton( onPressed: _takePhoto, child: Text("拍照"), ), RaisedButton( onPressed: _openGallery, child: Text("选择照片"), ), ], ), )); } /*图片控件*/ Widget _ImageView(imgPath) { if (imgPath == null) { return Center( child: Text("请选择图片或拍照"), ); } else { return Image.file( imgPath, ); } } /*拍照*/ _takePhoto() async { var image = await ImagePicker.pickImage(source: ImageSource.camera); setState(() { _imgPath = image; }); } /*相册*/ _openGallery() async { var image = await ImagePicker.pickImage(source: ImageSource.gallery); setState(() { _imgPath = image; }); } }
部分素材资源来源网站,本站提供免费下载,如有侵权请联系站长马上删除!