Chr*_*ris 2 image-gallery dart flutter imagepicker flutter-futurebuilder
我只是想选择一个图像并将其显示在我的应用程序中。为此,我使用Flutter Image Picker。我添加了所有依赖项,我可以选择图像,但无法显示它......
这是我尝试过的:
class _AddMemoryPageState extends State<AddMemoryPage> {
final picker = ImagePicker();
late Future<PickedFile?> pickedFile;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.secondary,
body: SafeArea(
child: Column(
children: [
Row(
children: [
Padding(
padding: EdgeInsets.only(
top: 15,
left: 25,
),
child: IconButtonWithExpandedTouchTarget(
onTapped: () {
Navigator.pop(context);
},
svgPath: 'assets/icons/down.svg',
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButtonWithExpandedTouchTarget(
onTapped: () async {
pickedFile = picker
.getImage(
source: ImageSource.camera,
)
.whenComplete(() => {setState(() {})});
},
svgPath: 'assets/icons/camera.svg',
),
SizedBox(
width: scaleWidth(50),
),
IconButtonWithExpandedTouchTarget(
onTapped: () async {
pickedFile = picker
.getImage(
source: ImageSource.gallery,
)
.whenComplete(() => {setState(() {})});
},
svgPath: 'assets/icons/gallery.svg',
),
],
),
FutureBuilder(
future: pickedFile,
builder: (context, data) {
if (data.hasData) {
return Container(
height: 200.0,
child: Image.file(
data.data as File,
fit: BoxFit.contain,
height: 200.0,
),
color: Colors.blue,
);
}
return Container(
height: 200.0,
color: Colors.blue,
);
},
),
],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
LateInitializationError:字段“pickedFile”尚未初始化。
我在这里缺少什么?处理这个问题的正确方法是什么?我找不到任何关于此的最新教程/文档..如果您需要更多信息,请告诉我!
小智 5
您基本上忘记了将 de PickerFile 转换为文件并初始化变量 PickerFile late Future<PickedFile?> pickedFile = Future.value(null);。
要转换文件中的 PickerFile,您只需执行以下操作:
File(data.data!.path)
Run Code Online (Sandbox Code Playgroud)
我对您的代码做了一些修改,现在可以显示图像:
File(data.data!.path)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13245 次 |
| 最近记录: |