1.添加依赖
在pubspec.yaml加入image_picker的依赖:
image_picker: ^0.6.0+9
2.在main.dart导入需要使用的包
import 'package:image_picker/image_picker.dart';
3.先实现一个FloatingActionButton
先实现一个FloatingActionButton用于触发图片选择,完整代码如下:
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _image;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Picker Example'),
),
body: Center(
child: _image == null
? Text('No image selected.')
: Image.file(_image),
),
floatingActionButton: FloatingActionButton(
onPressed:(){
},
tooltip: 'Pick Image',
child: Icon(Icons.add_a_photo),
),
);
}
}
效果如下:
4.实现FloatingActionButton的点击事件
在点击FloatingActionButton时弹出一个模仿ios效果的选择框,用于选择是拍照还是相册选择图片,代码如下:
onPressed:(){
showDemoActionSheet(
context: context,
child: CupertinoActionSheet(
title: const Text('Select photos'),
//message: const Text('Please select the best mode from the options below.'),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('Gallery'),
onPressed: () {
Navigator.pop(context, 'Gallery');
},
),
CupertinoActionSheetAction(
child: const Text('Camera'),
onPressed: () {
Navigator.pop(context, 'Camera');
},
),
],
cancelButton: CupertinoActionSheetAction(
child: const Text('Cancel'),
isDefaultAction: true,
onPressed: () {
Navigator.pop(context, 'Cancel');
},
),
),
);
},
showDemoActionSheet方法的实现如下:
void showDemoActionSheet({BuildContext context, Widget child}) {
showCupertinoModalPopup<String>(
context: context,
builder: (BuildContext context) => child,
).then((String value) {
if (value != null) {
if(value == "Camera"){
getImageByCamera();
}else if(value == "Gallery"){
getImageByGallery();
}
}
});
}
效果如下所示:
5.实现跳转相机拍照和相册选择图片方法
getImageByCamera()方法具体代码如下:
Future getImageByCamera() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = image;
});
}
getImageByGallery()方法具体代码如下:
Future getImageByGallery() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
});
}
以上,就是全部代码了!