Search code examples
flutterandroid-studiodartunhandled-exception

How to add File to Array (List) :Flutter


How to add File to Array (List)

I got an image from ImagePicker

var image = await ImagePicker.pickImage(source: imageSource);

_images are declared by followed

 List<File> _images = List<File>();

I tried as Follows

_images = image as List<File>

But I got errors like this

Unhandled Exception: type '_File' is not a subtype of type 'List' in type cast


Solution

  • You're getting the error because Future<File> pickImage(..) returns File not List<File>.

    In you code you're trying to cast File as List<File>:

    _images = image as List<File>
    

    If you only want to store the File returned from Future<File>pickImage(..), then you can add the File to the List

    _images.add(image);
    

    Also Future<File>pickedImage(..) method is deprecated so please try using Future<PickedFile> getImage(..), which returns PickedFile instead of File.