flutter - 如何在颤动中初始化 FutureBuilder 的后期变量?
问题描述
这是我的代码:
late Future<File> _imageFile; //define
body: FutureBuilder(
future: _imageFile,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
snapshot.data != null &&
_imageFile !=null) {
fileList.add(snapshot.data as File);
_imageFile =null as Future<File>;
}
return _bodyWidget();
},
),
当我运行项目时,抛出错误:LateInitializationError: Field '_imageFile@767230325' has not been initialized.
但是,如何初始化后面的变量?
我输入了这段代码:
late Future<PickedFile> _imageFile ;
@override
void initState() {
super.initState();
_imageFile = ImagePicker.platform.pickImage(source: ImageSource.gallery) as Future<PickedFile>;
}
它扔了
The following _CastError was thrown building Builder:
type 'Future<PickedFile?>' is not a subtype of type 'Future<PickedFile>' in type cast
解决方案
在回答IcyHerrscher
并阅读错误之后,我假设您忘记了 Dart 2.0 具有可空性并且您忘记了类型T
与T?
type 'Future<PickedFile?>' is not a subtype of type 'Future<PickedFile>' in type cast
所以只需添加?
到您要转换的类型
late Future<PickedFile?> _imageFile; /// add the ? so the result of the method ImagePicker.platform.pickImage is of the same type
@override
void initState() {
super.initState();
_imageFile = ImagePicker.platform.pickImage(source: ImageSource.gallery);
}
推荐阅读
- rust - 使用 rust 项目构建电子时遇到问题
- c# - 使用 c# 运行简单的 web 服务程序时 WcfTestClient 未打开,而是打开网页 - c# 编程新手
- java - 如何将数据从一个jsp表单传输到另一个
- java - Spring - 将图像作为字节数组存储在数据库中并检索它们
- jsp - 如何从 jsp 中的选择标记中维护选定的选项?
- sql - 选择带有“is null”子句的查询和子选择/左连接不返回任何结果
- java - 我无法使用 Selenium WebDriver 在 MakeMyTrip 网站中选择“来自城市”。输入文本“che”不选择指定城市
- reactjs - 使用 {react-select} 时无法读取未定义的属性“名称”
- android - 如何在将图像上传到服务器之前降低图像质量
- android - 如何编写一个“模块”来扩展现有的移动应用程序?