mohcine qachori
mohcine qachori

Reputation: 1

LateInitializationError: Field '_imagePicked@20490806' has not been initialized

Getting this when trying to initialize data.

 [The following LateError was thrown building UserImagePicker(dirty, state:
_UserImagePickerState#adbb9):
LateInitializationError: Field '_imagePicked@20490806' has not been initialized.]

Here's the code:

  late File _imagePicked;

  final _picker = ImagePicker();

  void _pickImage(ImageSource src) async {
    final pickedImageFile = await _picker.getImage(source: src);

    if (pickedImageFile != null) {
      setState(() {
        _imagePicked = File(pickedImageFile.path);
      });
    }
  }

Upvotes: 0

Views: 290

Answers (2)

Minsaf
Minsaf

Reputation: 274

Can you update the question where you call the _pickImage() function? I think when you call the function _pickImage(), there's nothing in the File _imagePicked. When you build the app, _imagePicked has nothing and this will cause the app to crash.

Upvotes: 0

cameron1024
cameron1024

Reputation: 10206

Nullable non-late fields in Dart are initialized to null:

String? string;
print(string);  // prints null

The same is not true of late fields. A late String cannot contain null, because null is not a valid value for the type String (which is the whole point of null safety).

Instead, late fields are uninitialized until they are first assigned. If you try to get the value of an uninitialized field, you get a LateInitializationError, rather than it returning null.

In your case, I suspect there is a line somewhere that contains:

if (_imagePicked == null) {
  // set _imagePicked
}

The easy fix is to simply make _imagePicked nullable. This gives 2 benefits:

  1. You don't have to store an extra boolean called _isImagePicked that tracks whether you have set this value

  2. The compiler will force you away from unsafe behaviour (like trying to call _imagePicked.foo() when _imagePicked is null)

Upvotes: 1

Related Questions