在 Flutter App 中使用相机和图库/照片选取图像
图像选择是我们经常需要的用户配置和其他内容的常见组件。我们将使用插件来实现。
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
image_picker: ^0.8.4
接下来,我们需要配置设置。对于Android平台,不需要任何东西。对于 iOS,打开在 ios/Runner 文件夹下找到的 Info.plist 文件,然后添加以下键。
<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to photo library</string>
<key>NSCameraUsageDescription</key>
<string>Allow access to camera to capture photos</string>
<key>NSMicrophoneUsageDescription</key>
<string>Allow access to microphone</string>
在我们的 StatefulWidget 的 State 类中,声明一个 File 变量来保存用户选取的图像。
File _image;
现在编写两个函数,分别通过相机和照片库选择图像。可选参数 imageQuality 接受 0 到 100 之间的任何值,你可以根据应用所需的大小和质量进行调整。获取图像文件后,我们将其保存到_image变量中并调用setState(),以便它可以显示在屏幕中。
_imgFromCamera() async {
File image = await ImagePicker.pickImage(
source: ImageSource.camera, imageQuality: 50
);
setState(() {
_image = image;
});
}
_imgFromGallery() async {
File image = await ImagePicker.pickImage(
source: ImageSource.gallery, imageQuality: 50
);
setState(() {
_image = image;
});
}
接下来,编写一个用于显示底部工作表的函数,供用户选择相机或图库选项。
void _showPicker(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Container(
child: new Wrap(
children: <Widget>[
new ListTile(
leading: new Icon(Icons.photo_library),
title: new Text('Photo Library'),
onTap: () {
_imgFromGallery();
Navigator.of(context).pop();
}),
new ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Camera'),
onTap: () {
_imgFromCamera();
Navigator.of(context).pop();
},
),
],
),
),
);
}
);
}
最后,让我们在屏幕上创建一个个人资料图片支架,该支架在单击时打开选择器,并显示所选图像。
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: <Widget>[
SizedBox(
height: 32,
),
Center(
child: GestureDetector(
onTap: () {
_showPicker(context);
},
child: CircleAvatar(
radius: 55,
backgroundColor: Color(0xffFDCF09),
child: _image != null
? ClipRRect(
borderRadius: BorderRadius.circular(50),
child: Image.file(
_image,
width: 100,
height: 100,
fit: BoxFit.fitHeight,
),
)
: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(50)),
width: 100,
height: 100,
child: Icon(
Icons.camera_alt,
color: Colors.grey[800],
),
),
),
),
)
],
),
);
}
全部完成,运行应用程序。