Flutter开发之图片选择器
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: '图片选择器示例',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _image;
final ImagePicker _picker = ImagePicker();
// 从相册选择图片
Future<void> _pickImageFromGallery() async {
final XFile image = await _picker.pickImage(
source: ImageSource.gallery,
);
if (image != null) {
setState(() {
_image = File(image.path);
});
}
}
// 从相机拍照选择图片
Future<void> _pickImageFromCamera() async {
final XFile image = await _picker.pickImage(
source: ImageSource.camera,
);
if (image != null) {
setState(() {
_image = File(image.path);
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('图片选择器示例'),
),
body: Center(
child: _image == null
? Text('没有选择图片')
: Image.file(_image),
),
floatingActionButton: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: FloatingActionButton(
onPressed: _pickImageFromGallery,
tooltip: '选择图片',
child: Icon(Icons.photo_library),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: FloatingActionButton(
onPressed: _pickImageFromCamera,
tooltip: '拍照',
child: Icon(Icons.camera_alt),
),
),
],
),
);
}
}
这段代码使用了image_picker
插件,实现了从相册和相机中选择图片的功能。用户可以通过点击底部的浮动按钮来选择图片,选择的图片会显示在屏幕中央。这是一个非常基础的图片选择器实现,适合作为学习Flutter的参考。
评论已关闭