从底部弹框显示拍照上传和相册选择图片上传
- 加入权限: …android\app\src\main\AndroidManifest.xml 中的 manifest 下面加入
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
- 主要代码
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';
class ExpressDelivery extends StatefulWidget {
ExpressDelivery({Key key}) : super(key: key);
_ExpressDelivery createState() => _ExpressDelivery();
}
class _ExpressDelivery extends State<ExpressDelivery> {
File _image;
bool showPicture = true;
@override
Widget build(BuildContext context) {
if (_image != null) {
showPicture = false;
print('我不是空');
}
return Scaffold(
appBar: AppBar(
title: Text('拍照'),
),
body: Center(
child: Column(children: [
Padding(
padding: EdgeInsets.only(top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Offstage(
offstage: showPicture,
child: Container(
width: 160,
height: 160,
color: Colors.black,
child: _buildImage(),
),
),
SizedBox(
width: 160,
height: 160,
child: ElevatedButton(
onPressed: () {
_handleClickMe(context);
},
child: const Text('拍照'),
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8))),
backgroundColor:
MaterialStateProperty.all(Colors.lightBlue)),
),
)
],
),
),
]),
));
Future<void> _handleClickMe(BuildContext context) async {
return showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) {
return CupertinoActionSheet(
title: Text('上传图片'),
message: Text('请选择上传方式'),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text('拍照上传'),
onPressed: () {
_takePhoto();
Navigator.pop(context);
},
),
CupertinoActionSheetAction(
child: Text('相册'),
onPressed: () {
_openGallery();
Navigator.pop(context);
},
),
],
cancelButton: CupertinoActionSheetAction(
isDefaultAction: true,
child: Text('取消'),
onPressed: () {
Navigator.pop(context);
},
),
);
},
);
}
_takePhoto() async {
var image = await ImagePicker()
.getImage(source: ImageSource.camera, maxWidth: 150, maxHeight: 150);
this._uploadImage(File(image.path));
_image = File(image.path);
setState(() {
this._image = File(image.path);
});
}
_openGallery() async {
var image = await ImagePicker()
.getImage(source: ImageSource.gallery, maxWidth: 150, maxHeight: 150);
_image = File(image.path);
setState(() {
this._image = File(image.path);
});
}
Widget _buildImage() {
if (this._image == null) {
return Text("请选择图片...");
}
return Image.file(this._image);
}
_uploadImage(File _imageDir) async {
var fileDir = _imageDir.path;
FormData formData = FormData.fromMap({
"pathName": fileDir.split('/').last,
"file": await MultipartFile.fromFile(fileDir, filename: "xxx.jpg")
});
var response = await Dio().post(
"http://存放地址(也就是后端接收的地址)",
data: formData);
print("让我康康");
print(response);
}
}
- 成功后的图片