import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class PhotoApp extends StatefulWidget {
@override
_PhotoAppState createState() => _PhotoAppState();
}
class _PhotoAppState extends State<PhotoApp> {
List<File> _image=[];//因为不止添加一张图片,所以我们用List
Future getImage(bool isTakeImg) async {
Navigator.pop(context);//选择完照片后,底部的栏会自动收回去
var image = await ImagePicker.pickImage(
source: isTakeImg ? ImageSource.camera : ImageSource.gallery);
if(image!=null)//有可能你点了拍照但最后没上传,返回了,所以要确认你是否上传了图片,如果没有就不用后面的操作了,自己亲身经历,如果不这样的话会报错
{
setState(() {
_image.add(image);//把上传的图片放到我们的图片List中去
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('伙计,拍个照么'),
),
body: Center(
child: Wrap(
spacing: 5,
runSpacing: 5,
children: _imgLayout(),//图片页面总布局,单独写方法,减少嵌套,避免恶心
),
),
floatingActionButton: FloatingActionButton(
onPressed: _pickImage,//减少嵌套,避免恶心
tooltip: '选择图片',
child: Icon(Icons.add_a_photo),
),
);
}
_pickImage() {
showModalBottomSheet(//这个字面意思大家应该都懂
context: context,
builder: (context) => Container(
height: 160.0,
child: Column(
children: <Widget>[
_item('拍照', true),
_item('从相册选择', false),
],
),
));
}
_item(String title, bool isTakeImg) {
return GestureDetector(
child: ListTile(
leading: Icon(isTakeImg ? Icons.camera_alt : Icons.photo_library),//妙
title: Text(title),
),
onTap: () => getImage(isTakeImg),
);
}
_imgLayout() {
return _image.map((file){//至于为什么要.map,应该是要遍历叭
return Stack(
children: <Widget>[
//图片圆角效果
ClipRRect(
borderRadius: BorderRadius.circular(5),//图片也要稍微修饰一哈
child: Image.file(file,width: 120,height: 90,fit: BoxFit.fill,),
),
Positioned(//右上角的关闭按钮
right: 5,
top: 5,
child: GestureDetector(//是一个手势监听器哦
onTap: (){
setState(() {
_image.remove(file); //作用就是从图片List中删除选中要删除的img
});
},
child: ClipOval(//圆的伙计
child: Container(
padding: EdgeInsets.all(3),
decoration: BoxDecoration(color: Colors.black26),//关闭按钮不能太黑,丑
child: Icon(Icons.close,size: 18,color:Colors.white),
),
),
),
)
],
);
}).toList();//!!!巨坑,需要转化为List,因为上面children后面本来就是个Widget[]
}
}