PUb包地址:https://pub.dev/packages/image_picker
介绍:Flutter 插件,用于从 Android 和 iOS 图像库中选择图像,并使用相机拍摄新照片。
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
main() {
runApp(mater());
}
class mater extends StatefulWidget {
const mater({Key? key}) : super(key: key);
@override
State<mater> createState() => _materState();
}
class _materState extends State<mater> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ImagePickerPage(),
);
}
}
class ImagePickerPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _ImagePickerState();
}
}
class _ImagePickerState extends State<ImagePickerPage> {
var _imgPath;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("ImagePicker"),
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_ImageView(_imgPath),
RaisedButton(
onPressed: _takePhoto,
child: Text("拍照"),
),
RaisedButton(
onPressed: _openGallery,
child: Text("单选照片"),
),
RaisedButton(
onPressed: _openGalleryall,
child: Text("多选照片"),
),
RaisedButton(
onPressed: _shoot,
child: Text("拍摄视频"),
),
RaisedButton(
onPressed: _openmp4,
child: Text("单选视频"),
),
],
),
));
}
/*图片控件*/
Widget _ImageView(imgPath) {
if (imgPath == null) {
return Center(
child: Text("请选择图片或拍照"),
);
} else {
return Image.file(
File(imgPath),
);
}
}
// source 类型=>
// /// 指定拾取图像的来源。
// enum ImageSource {
// /// 打开设备相机,让用户拍摄一张新照片。
// camera,
// /// 打开用户的照片库。
// gallery,
// }
/*拍照*/
_takePhoto() async {
var image = await ImagePicker.platform
.pickImage(source: ImageSource.camera, maxWidth: 400);
setState(() {
_imgPath = image?.path;
});
print(image?.path); //图片路径
}
/*单选图片相册*/
_openGallery() async {
var image =
await ImagePicker.platform.pickImage(source: ImageSource.gallery);
setState(() {
_imgPath = image?.path;
});
print(image?.path); //图片路径
}
/*多选图片相册*/
_openGalleryall() async {
var image = await ImagePicker.platform.pickMultiImage();
print(image); //一个list
}
/**
* 下面是视频操作
*/
/*拍摄视频*/
_shoot() async {
var image =
await ImagePicker.platform.pickVideo(source: ImageSource.camera);
print(image?.path); //一个list
}
/*选择视频*/
_openmp4() async {
var image =
await ImagePicker.platform.pickVideo(source: ImageSource.gallery);
print(image?.path); //一个list
}
}
THE END