import 'package:flutter/material.dart';
//导入拍照插件
import 'package:image_picker/image_picker.dart';
//导入文件操作库
import 'dart:io';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
//flutter项目必须返回MaterialApp,flutter项目从MaterialApp组件开始
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: MyHomePage(title: '手机相册'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
//用户选择的照片
File _image;
Future choosePic(ImageSource source) async { //参数类型为ImageSource
var image = await ImagePicker.pickImage(source: source);
setState(() {
//将用户照片存储到_image
_image=image;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
//appBar订制导航条
appBar: renderAppBar(),
body: renderBody(),
floatingActionButton:renderFloatingActionBar(),
);
}
//渲染头部的Appbar
Widget renderAppBar(){
return AppBar(
title:Text(widget.title),
centerTitle: true,
);
}
//渲染页面主体区域
Widget renderBody(){
if(_image==null){
return Center(child:Text("请选择照片!"),) ;
}
return Image.file(_image,fit: BoxFit.cover,width: double.infinity,height: double.infinity,);
}
//渲染底部浮动按钮
Widget renderFloatingActionBar(){
return ButtonBar(
//设置对齐方式
alignment: MainAxisAlignment.spaceAround,
children: [
//第一个浮动按钮
FloatingActionButton(
onPressed: (){
choosePic(ImageSource.camera);
},
tooltip: 'photo_camera',
child: Icon(Icons.photo_camera), //相机拍照
),
//第二个浮动按钮
FloatingActionButton(
onPressed: (){
choosePic(ImageSource.gallery);
},
tooltip: 'photo_libarary',
child: Icon(Icons.photo_library), //选择相册照片
)
],
);
}
}