前言:image_picker可以camera拍照,也可以从gallery相册中选择。 1.导入库:image_picker: ^0.7.4 2.demo:
class MyIndexedStack extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return _MyIndexedStack();
}
}
class _MyIndexedStack extends State<MyIndexedStack>{
int _pageIndex = 0;
final ImagePicker picker = new ImagePicker();
String str11 = "http://pic1.win4000.com/pic/2/4e/f0a80319bd.jpg";
var str1 ;
String str22 = "http://pic1.win4000.com/pic/d/dc/95bb6142d5_250_350.jpg";
var str2 ;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: IndexedStack(
children: [
str1==null?Image.network(str11):Image.file(File(str1),fit: BoxFit.fill,),
str2==null?Image.asset('assets/images/person_top_bg.jpg'):Image.file(File(str2),fit: BoxFit.fill,),
],
index: _pageIndex,
),
floatingActionButton: FloatingActionButton(
onPressed: (){
_pageIndex = _pageIndex==0?1:0;
if(_pageIndex==1){
_getCameraImage();
}else{
_getGalleryImage();
}
setState(() {
});
},
child: Icon(Icons.add),
),
)
);
}
//进入系统相机拍照,str1就是拍的图片的路径
Future _getCameraImage() async{
final cameraImages = await picker.getImage(source: ImageSource.camera);
if(mounted){
setState(() {
if(cameraImages!=null){
str1 = cameraImages.path;
print('camera路径为:${cameraImages.path}');
}
});
}
}
//进入系统相册,str2就是选择的图片的地址
Future _getGalleryImage() async{
final galleryImages = await picker.getImage(source: ImageSource.gallery);
if(mounted){
setState(() {
if(galleryImages!=null){
str2 = galleryImages.path;
print('gallery路径为:${galleryImages.path}');
}
});
}
}
}
//从网络上读取 Image.network(str11):Image.file(File(str1),fit: BoxFit.fill,) //从本地应用内读取 Image.asset(‘assets/images/person_top_bg.jpg’) //从手机内存中读取 Image.file(File(str2),fit: BoxFit.fill,)
|