在最近的开发中,需要做一个选择图片(包括拍照和相册选择)然后上传的功能,我们的项目是iOS原生和flutter混编的,首先用flutter实现这个页面,选择了第三方插件image_picker,下面先看一下效果图
下面我们开始一步一步实现这个页面的逻辑,核心是在实现一个可复用的图片选择控件,支持设置最大选择图片数maxCount,支持删除。
第一步:集成image_picker ,导入图片资源(就是导入那个相机的icon和删除的icon这里就不展开说了)
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
image_picker: 0.6.0+8
我这里用的是0.6.0+8版本,可以自行选择最新版本,然后以iOS为例,需要添加访问相册的权限
Add the following keys to your Info.plist file, located in <project root>/ios/Runner/Info.plist
:
-
NSPhotoLibraryUsageDescription
- describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
-
NSCameraUsageDescription
- describe why your app needs access to the camera. This is called Privacy - Camera Usage Description in the visual editor.
-
NSMicrophoneUsageDescription
- describe why your app needs access to the microphone, if you intend to record videos. This is called Privacy - Microphone Usage Description in the visual editor
然后再用到的页面中 import 'package:image_picker/image_picker.dart';
第二步:根据需求封装一个图片选择控件,我这里是一行三张图片的布局,删除按钮在右上角
首先分析一下需求:
1.支持两种样式,有图片或者上传样式
2.在有图片的样式时,才显示右上角的删除icon
3.在上传样式时,点击弹出一个选择相机/相册的菜单(iOS中的ActionSheet)
4.图片样式时,点击预览大图(这个还没实现,后续有时间再更新)
需求理清晰了就可以开始撸码:
class UploadImageItem extends StatelessWidget {
final GestureTapCallback onTap;
final Function callBack;
final UploadImageModel imageModel;
final Function deleteFun;
UploadImageItem({this.onTap, this.callBack, this.imageModel, this.deleteFun});
@override
Widget build(BuildContext context) {
return Container(