It's my code:
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();
},
),
when I run the project , is throw error: LateInitializationError: Field '_imageFile@767230325' has not been initialized.
But , how can I initialize the later variable?
and I put in this code :
late Future<PickedFile> _imageFile ;
@override
void initState() {
super.initState();
_imageFile = ImagePicker.platform.pickImage(source: ImageSource.gallery) as Future<PickedFile>;
}
It throwed
The following _CastError was thrown building Builder:
type 'Future<PickedFile?>' is not a subtype of type 'Future<PickedFile>' in type cast
CodePudding user response:
You can initialize your code in the initstate of StatefulWidget, like so.
class Testing extends StatefulWidget {
const Testing({Key? key}) : super(key: key);
@override
_TestingState createState() => _TestingState();
}
class _TestingState extends State<Testing> {
late Future<Your_type> myFuture;
@override
void initState() {
super.initState();
myFuture = YourQueryMethod;
}
@override
Widget build(BuildContext context) {
}
}
CodePudding user response:
Following the answer of IcyHerrscher
and reading the error I assume you forgot that Dart 2.0 has nullability and you forgot a type T
is not the same as T?
type 'Future<PickedFile?>' is not a subtype of type 'Future<PickedFile>' in type cast
so just add ?
to the type you want to 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);
}