本文共 2327 字,大约阅读时间需要 7 分钟。
需求: image_picker的使用,点击按钮底部弹出 相册、拍照选择框,实现具体功能
1:引入插件
pubspec.yaml 增加image_picker: ^0.7.5+2
2:android 添加androidx兼容
gradle.properties 增加
android.useAndroidX=trueandroid.enableJetifier=true
build 添加依赖
androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' testImplementation 'androidx.test:core:1.2.0'
3: ios ->Runner->info.plist添加权限说明
NSCameraUsageDescription 这是你的自拍照 NSMicrophoneUsageDescription 用于音频插件 NSPhotoLibraryUsageDescription 用于相册选择插件 UIBackgroundModes remote-notification
4:编写Ui
添加一个浮动按钮,增加点击事件弹出相册/拍照选择框具体如下:floatingActionButton: FloatingActionButton( child: Center( child: Text( "点我", style: TextStyle(color: Colors.white), )), backgroundColor: Colors.blueAccent, elevation: 0.2, onPressed: () { //点击事件 showPicker(); }, )
//弹出选择相册/拍照对话框 showPicker() { //底部弹出 showModalBottomSheet( context: context, builder: (BuildContext con) => Container( height: 160, padding: EdgeInsets.all(20), color: Colors.white, child: Expanded( child: ListView( children: [createItem(true, "拍照"), createItem(false, "相册")], ), ), )); }//创建item Widget createItem(bool state, String name) { return GestureDetector( onTap: () { //点击事件处理 openPicker(state); }, child: ListTile( leading: Icon(state ? Icons.camera : Icons.image), title: Text(name), )); }//使用imagePicker异步打开拍照 、相册 openPicker(bool state) async { //销毁底部弹出框 Navigator.pop(context); var picker = ImagePicker(); //根据状态标识决定打开相机还是相册 var future = await picker.getImage( source: state ? ImageSource.camera : ImageSource.gallery); setState(() { //通过setstate 通知重绘更新 file = File(future.path); }); }
拿到了图片,那么就差左后一步了,实现body 添加Image 显示图片,代码如下:
body: Container( alignment: Alignment.center, margin: EdgeInsets.all(20), //没有图片时候显示占位图 child: file == null ? Icon(Icons.image,) : Image.file(file), )
转载地址:http://amkgf.baihongyu.com/