Flutter获取相册中的图片和用相机拍照
在原生开发中,拍照及从图库选择图片是非常常见的需求,而且原生的图片选择第三方库也有很多并且很完善了。
Flutter也给我们提供了好用的图片选择插件,ios和Android都能用的
image_picker
Flutter拍照:
Flutter选择图片:
使用方法
一、在pubspec.yaml加入image_picker的依赖,版本号在github上找最新的即可。
如下:
添加完依赖,在VSCODE,直接Ctrl+s保存,会自动get到本地。
二、IOS中要获取权限:
找到:
<project root>/ios/Runner/Info.plist,添加下面代码,描述自己根据需求写即可:
1 | < key >NSPhotoLibraryUsageDescription</ key > |
2 | < string >XXX需要获取相册权限</ string > |
3 | < key >NSCameraUsageDescription</ key > |
4 | < string >XXX需要获取相机权限</ string > |
5 | < key >NSMicrophoneUsageDescription</ key > |
6 | < string >XXX需要获取麦克风权限</ string > |
三、导包
1 | import 'package:image_picker/image_picker.dart' ; |
四、使用
拍照
1 | var image = await ImagePicker.pickImage(source: ImageSource.camera); |
相册
1 | var image = await ImagePicker.pickImage(source: ImageSource.gallery); |
五、完整代码:
01 | import 'package:flutter/material.dart' ; |
03 | import 'package:image_picker/image_picker.dart' ; |
05 | class ImagePickerWidget extends StatefulWidget { |
07 | State<StatefulWidget> createState() { |
08 | return _ImagePickerState(); |
12 | class _ImagePickerState extends State<ImagePickerWidget> { |
16 | Widget build(BuildContext context) { |
19 | title: Text( "ImagePicker" ), |
21 | body: SingleChildScrollView( |
26 | onPressed: _takePhoto, |
30 | onPressed: _openGallery, |
39 | Widget _ImageView(imgPath) { |
40 | if (imgPath == null ) { |
42 | child: Text( "请选择图片或拍照" ), |
54 | var image = await ImagePicker.pickImage(source: ImageSource.camera); |
62 | _openGallery() async { |
63 | var image = await ImagePicker.pickImage(source: ImageSource.gallery); |
部分素材资源来源网站,本站提供免费下载,如有侵权请联系站长马上删除!