首页 > 解决方案 > 如何在颤动中初始化 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

标签: flutter

解决方案


在回答IcyHerrscher并阅读错误之后,我假设您忘记了 Dart 2.0 具有可空性并且您忘记了类型TT?

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);
  }

推荐阅读