在FlutterApp中使⽤相机和图库flutter的图像选择[Flutter专题12]感谢您抽出..来阅读本⽂flutter sdk
⼤家好。我是坚果,这是我的“坚果前端”,觉得不错的话,关注⼀下吧,如果你迷惘,
不妨看看码农的轨迹
在 Flutter App 中使⽤相机和图库/照⽚选取图像
图像选择是我们经常需要的⽤户配置和其他内容的常见组件。我们将使⽤插件来实现。
步骤 1 — 将依赖项添加到pubspec.yaml⽂件。
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
image_picker: ^0.8.4
步骤 2 - 配置各平台
接下来,我们需要配置设置。对于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>
步骤 3 — 图像选取功能
在我们的 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;
});
}
步骤4 - 创建⽤于选择相机/图库的选项选择
接下来,编写⼀个⽤于显⽰底部⼯作表的函数,供⽤户选择相机或图库选项。
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();
},
),
],
),
),
);
}
);
}
步骤 5 - 在屏幕上创建和配置图像视图
最后,让我们在屏幕上创建⼀个个⼈资料图⽚⽀架,该⽀架在单击时打开选择器,并显⽰所选图像。
@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: [200],
borderRadius: BorderRadius.circular(50)),
width: 100,
height: 100,
child: Icon(
Icons.camera_alt,
color: [800],
),
),
),
),
)
],
)
,
);
}
全部完成,运⾏应⽤程序,
好的,今天的分享到这⼉就和⼤家说再见了,感谢⼤家的阅读