提交 318e93fc authored 作者: shixiaochen's avatar shixiaochen

1、Android适配选择图片(相机、相册);

上级 27437e9f
...@@ -17,7 +17,7 @@ class _MyAppState extends State<MyApp> { ...@@ -17,7 +17,7 @@ class _MyAppState extends State<MyApp> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return MaterialApp(
home: HomePage(), home: const HomePage(),
theme: ThemeData.light().copyWith( theme: ThemeData.light().copyWith(
appBarTheme: const AppBarTheme( appBarTheme: const AppBarTheme(
backgroundColor: Colors.blue, backgroundColor: Colors.blue,
......
import 'dart:io'; import 'dart:io';
import 'package:feedback_complaint_plug/widget/select_image_dialog.dart';
import 'package:file_picker/file_picker.dart'; import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:image/image.dart' as image; import 'package:image/image.dart' as image;
...@@ -102,31 +103,11 @@ class _ComplaintWebPageState extends State<ComplaintWebPage> { ...@@ -102,31 +103,11 @@ class _ComplaintWebPageState extends State<ComplaintWebPage> {
/// Android选择图片 /// Android选择图片
Future<List<String>> _androidFilePicker(FileSelectorParams params) async { Future<List<String>> _androidFilePicker(FileSelectorParams params) async {
debugPrint("params-->$params"); debugPrint("params-->${params.acceptTypes}");
if (params.acceptTypes.any((type) => type == 'image/*')) { if (params.acceptTypes.any((type) => type == 'image/*')) {
if (!await _requestPermissionCam()) { var result = await _showImagePicker(context);
ToastUtil.showToast("需要相机权限才能使用该功能,请到设置中开启"); debugPrint("result-->$result");
return []; return result;
}
var photo = await ImagePicker()
.pickImage(source: ImageSource.gallery, imageQuality: 20);
if (photo == null) {
return [];
}
final imageData = await photo.readAsBytes();
final decodedImage = image.decodeImage(imageData)!;
final scaledImage = image.copyResize(decodedImage, width: 500);
final jpg = image.encodeJpg(scaledImage, quality: 90);
final filePath = (await getTemporaryDirectory()).uri.resolve(
'./image_${DateTime.now().microsecondsSinceEpoch}.jpg',
);
final file = await File.fromUri(filePath).create(recursive: true);
await file.writeAsBytes(jpg, flush: true);
debugPrint("file = ${file.uri.toString()}");
return [file.uri.toString()];
} else if (params.acceptTypes.any((type) => type == '' || type == "*/*")) { } else if (params.acceptTypes.any((type) => type == '' || type == "*/*")) {
if (!await _requestPermissionStorage()) { if (!await _requestPermissionStorage()) {
ToastUtil.showToast("需要访问存储权限才能使用该功能,请到设置中开启"); ToastUtil.showToast("需要访问存储权限才能使用该功能,请到设置中开启");
...@@ -148,16 +129,44 @@ class _ComplaintWebPageState extends State<ComplaintWebPage> { ...@@ -148,16 +129,44 @@ class _ComplaintWebPageState extends State<ComplaintWebPage> {
return []; return [];
} }
/// 获取相机权限 /// 选择图片底部弹框
Future<bool> _requestPermissionCam() async { Future<List<String>> _showImagePicker(context) async {
final permissions = await Permission.camera.request(); ImageSource source = ImageSource.gallery;
await showModalBottomSheet(
backgroundColor: Colors.transparent,
isScrollControlled: true,
context: context,
builder: (BuildContext context) {
return SelectImageDialog(onCallback: (imageSource) async {
source = imageSource;
debugPrint("imageSource-->$source");
Navigator.pop(context);
});
},
);
var list = await _convertImagePicker(source);
return list;
}
if (permissions.isGranted) { /// 图片转换
return true; Future<List<String>> _convertImagePicker(ImageSource source) async {
} else { var photo = await ImagePicker().pickImage(source: source, imageQuality: 20);
ToastUtil.showToast('需要相机权限!'); // 未选择图片时 返回值为null,不需要增加提示信息
return false; if (photo == null) {
return [];
} }
final imageData = await photo.readAsBytes();
final decodedImage = image.decodeImage(imageData)!;
final scaledImage = image.copyResize(decodedImage, width: 500);
final jpg = image.encodeJpg(scaledImage, quality: 90);
final filePath = (await getTemporaryDirectory()).uri.resolve(
'./image_${DateTime.now().microsecondsSinceEpoch}.jpg',
);
final file = await File.fromUri(filePath).create(recursive: true);
await file.writeAsBytes(jpg, flush: true);
debugPrint("file = ${file.uri.toString()}");
return [file.uri.toString()];
} }
/// 获取存储权限 /// 获取存储权限
......
import 'dart:io';
import 'package:feedback_complaint_plug/utils/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
/// 选择图片(相机、相册)
class SelectImageDialog extends StatelessWidget {
final String? title;
final Function onCallback;
const SelectImageDialog({super.key, this.title, required this.onCallback});
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 10.0),
_cardContainer(children: [
_buttonItem(
title: "拍照",
onTap: () async {
await _selectPic(ImageSource.camera, onCallback);
}),
const Divider(height: 1.0),
_buttonItem(
title: "从相册选择",
onTap: () async {
await _selectPic(ImageSource.gallery, onCallback);
}),
]),
const SizedBox(height: 10.0),
_cardContainer(children: [
_buttonItem(
title: "取消",
onTap: () => Navigator.pop(context),
)
]),
const SizedBox(height: 10.0),
],
);
}
/// 圆角卡片
_cardContainer({required List<Widget> children}) {
return Container(
width: double.infinity,
margin: const EdgeInsets.symmetric(horizontal: 20.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10.0),
),
child: Column(
children: children,
),
);
}
/// 按钮
_buttonItem({title, onTap}) {
return InkWell(
onTap: onTap,
child: Container(
constraints: const BoxConstraints(minHeight: 45.0),
alignment: Alignment.center,
child: Text(
title ?? "",
style: const TextStyle(
fontSize: 14.0,
color: Color(0xFF212121),
fontWeight: FontWeight.bold),
),
),
);
}
/// 选择和加载图片
Future<void> _selectPic(ImageSource source, onSuccess) async {
if (Platform.isIOS) {
switch (source) {
case ImageSource.gallery:
await _galleryIOS(source, onSuccess);
break;
case ImageSource.camera:
await _cameraIOS(source, onSuccess);
break;
}
} else {
await _callbackImage(source, onSuccess);
}
}
_galleryIOS(ImageSource source, onSuccess) async {
if (await _requestPermissionPhotos()) {
_callbackImage(source, onSuccess);
} else {
if (await _requestPermissionPhotosAddOnly()) {
_callbackImage(source, onSuccess);
} else {
ToastUtil.showToast("无法访问相册中的照片,请前往系统设置!");
return;
}
}
}
_cameraIOS(ImageSource source, onSuccess) async {
if (await _requestPermissionCam()) {
_callbackImage(source, onSuccess);
} else {
ToastUtil.showToast("无法访问相机,请前往系统设置!");
return;
}
}
Future<void> _callbackImage(ImageSource source, onSuccess) async {
onCallback.call(source);
}
Future<bool> _requestPermissionPhotos() async {
final permissions = await Permission.photos.request();
if (permissions.isGranted) {
return true;
} else {
ToastUtil.showToast('需要相册权限!');
return false;
}
}
Future<bool> _requestPermissionPhotosAddOnly() async {
final permissions = await Permission.photosAddOnly.request();
if (permissions.isGranted) {
return true;
} else {
ToastUtil.showToast('需要相册权限!');
return false;
}
}
Future<bool> _requestPermissionCam() async {
final permissions = await Permission.camera.request();
if (permissions.isGranted) {
return true;
} else {
ToastUtil.showToast('需要相机权限!');
return false;
}
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论