官方插件:https://pub.dev/packages/image_picker
1. 可以通过官方插件获取本地相册
第一步:pubspec文件导入依赖
dependencies:
image_picker: ^0.6.7+21
第二部:添加权限(否则会有闪退现象)
-
iOS打开项目在plist文件中配置权限如下:
第三步:代码
- 通过ImageSource.gallery/ImageSource.camera来切换相册和相机
class _TestNativeAlbumState extends State<TestNativeAlbum> {
File _albumImage;
final picker = ImagePicker();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("获取原生相册"),
),
body: Column(
children: [
_albumImage == null?Text("暂无图片"):Image.file(_albumImage),
RaisedButton(
child: Text("从相册获取图片"),
onPressed: _getImage,
),
],
),
);
}
Future _getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_albumImage = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
}
效果