最近要做个上传图片的操作,想要实现以下弹出效果,我觉得挺简单就去网上翻,也没找到个简单现成的。我把自己刚写好的贴出来,这样下次我就能百度到自己了,自己写是不可能的,严格遵守面向百度编程原则。
引用插件:
image_picker: ^0.8.6
调用:
File? choseFile = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
有一点注意,由于取消选择或点击阴影部分,chosePhotoOnAlbumOrCamera方法会返回null,要记得考虑这种情况,特别是已经选择过一张照片需要二次选择的时候。
附代码:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class ImageUtils {
/**
* 选择图片
*/
static Future<File?> getImage({required ImageSource source, int quality = 100}) async {
XFile? file = await ImagePicker().pickImage(source: source, imageQuality: quality);
if (file == null) {
return null;
} else {
return File(file.path);
}
}
static Future<File?> chosePhotoOnAlbumOrCamera({required BuildContext context}) async {
File? file;
await showModalBottomSheet(
context: context,
backgroundColor: Colors.transparent,
builder: (context) {
return Container(
decoration:
BoxDecoration(color: Colors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(10))),
width: MediaQuery.of(context).size.width,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
InkWell(
onTap: () async {
file = await getImage(source: ImageSource.camera);
Navigator.pop(context);
},
child: Container(padding: EdgeInsets.symmetric(vertical: 15), child: Text("拍照"))),
Divider(height: 1),
InkWell(
onTap: () async {
file = await getImage(source: ImageSource.gallery);
Navigator.pop(context);
},
child: Container(padding: EdgeInsets.symmetric(vertical: 15), child: Text("相册"))),
Divider(height: 1, color: Colors.black),
InkWell(
onTap: () {
Navigator.pop(context);
},
child: Container(padding: EdgeInsets.symmetric(vertical: 15), child: Text("取消")),
),
],
),
);
});
return file;
}
}