提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
1. 引入插件image_picker
在项目的配置文件pubspec.yaml中的环境依赖dependencies下引入插件image_picker,最新版本号可以从 https://pub.flutter-io.cn/ 网页查询。
dependencies:
image_picker: ^0.6.7+17
image_picker: ^0.8.6 #新版本
由于技术的更新换代非常快,每个版本相应的API均会有所更新,下面是官方文档中的新旧API的对比。对应链接:image_picker插件官方文档
2. showBottomMenu函数(^0.6.7+17版本)
showBottomMenu()函数可以用于某按钮或手势的onTap()、onPress()事件中调用,即可弹出从屏幕底部滑起组件并点击调用照相机和图库功能。
void showBottomMenu(context){
showModalBottomSheet(context: context, builder: (context){
return Container(
height: 200,
child: Column(
children: [
ListTile(
title: Text('拍照',textAlign: TextAlign.center,style: TextStyle(fontSize: 19),),
onTap: () async{
//takePhotoFromCamera();
final ImagePicker picker = new ImagePicker();
var image = await picker.getImage(source: ImageSource.camera);
}),
Divider(),
ListTile(
title: Text('从相册中选择',textAlign: TextAlign.center,style: TextStyle(fontSize: 19),),
onTap: () async{
//print('00000');
//takePhotoFromGallery();
final ImagePicker picker = new ImagePicker();
var image = await picker.getImage(source: ImageSource.gallery);
}),
Divider(),
ListTile(
title: Text('取消',textAlign: TextAlign.center,style: TextStyle(fontSize: 19),),
onTap: (){
Navigator.of(context).pop();//取消滑块的滑起
})
],
),
);
});
}
3. 调用照相机和图库的核心代码
调用照相机和图库的代码区别不大,区别在于getImage属性的参数,调用相机的参数为mageSource.camera,而调用相册的参数为ImageSource.gallery。
3.1 image_picker: ^0.6.7+17
版本下
//调用手机相机
final ImagePicker picker = new ImagePicker();
var image = await picker.getImage(source: ImageSource.camera);
//调用手机相册
final ImagePicker picker = new ImagePicker();
var image = await picker.getImage(source: ImageSource.gallery);
3.2 image_picker: ^0.8.6
版本下
final ImagePicker picker = new ImagePicker();
//var image = await picker.getImage(source: ImageSource.gallery);
final XFile? image = await picker.pickImage(source: ImageSource.gallery);
setState(() {
imagePath = image;
});