第三方插件支持
-
camera
支持自定义相机 -
image_picker
支持相册图片选择及拍照功能
image_picker
- 安装
在pubspec.yaml
文件中新增依赖
dependencies:
...
image_picker: ”0.6.0+8“
不确定版本可以写成image_picker: any
下载成功后查看pubspec.lock
文件获取明确版本号替换pubspec.yaml文件内版本号,及时替换防止依赖版本号不明确造成不必要的报错
- 设置ios权限
找到Info.plist文件项目根目录/ios/Runner/Info.plist
添加以下keys
-
NSPhotoLibraryUsageDescription
调取照片库的权限描述 -
NSCameraUsageDescription
访问相机的描述 -
NSMicrophoneUsageDescription
访问麦克风的描述
- 设置android权限
- API 29+ : 无需配置插件
- API <29
项目根目录/android/app/src/main/AndroidManifest.xml
和项目根目录/android/app/src/debug/AndroidManifest.xml
文件中为<application>标签中增加android:requestLegacyExternalStorage="true"
属性
- 使用(旧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('从相册选择'),
),
)
]),
}
- 使用(新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);
});
}
}