如何解决Flutter Image Picker 不从相册/图库中选择图像
我正在尝试在我的应用中实现 imagepicker 库。我的应用程序运行没有任何错误,但我无法从相册/画廊中挑选/选择图像。在选择图像时,应用程序应该在正文中显示图像,但没有任何反应。我必须点击取消才能返回主屏幕。我还应该提到,控制台为打印语句 null
print('image: $image');
请帮忙。
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter/material.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: 'Flutter Demo',theme: ThemeData(
brightness: Brightness.dark,),home: MyHomePage(),);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File image;
final picker = ImagePicker();
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
image = File(pickedFile.path);
} else {
print('image: $image');
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Picker'),body: Center(
child: image == null
? Text('No image selected.')
: Image.file(image),floatingActionButton: FloatingActionButton(
onPressed: getImage,tooltip: 'Pick Image',child: Icon(Icons.add_a_photo),);
}
}
解决方法
试试下面的代码
Future getImage() async {
File pickedFile = await picker.getImage(source: ImageSource.gallery);
if (pickedFile != null) {
setState(() {
image = File(pickedFile.path);
});
} else {
print('image: $image');
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。