flutterdarterror-handlingflutter-image-picker

What does the error "type 'Future<dynamic>' is not a subtype of type 'XFile'" mean in Flutter?


I'm trying to convert an image or XFile from image_picker to an inputImage for a different library. The full error message is: ======== Exception caught by gesture =============================================================== The following _TypeError was thrown while handling a gesture: type 'Future< dynamic>' is not a subtype of type 'XFile'

These are the 3 methods that I've been using to do this. I've tried several things, but I keep getting this error.

GetImage() async {
  print("getImage");
  final ImagePicker _picker = ImagePicker();
  final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
  return photo;
}

changeFile(XFile image) async{
  File? file = File(image!.path);
  return file;
}

getData(File file) async{
  TextRecognition textRecognition = TextRecognition();
  //final inputImage = _processImageFile(image);
  final inputImage = InputImage.fromFile(file);
  var result = await textRecognition.process(inputImage);
  print(result);
}

I call it with:

XFile photo = GetImage();
File file = changeFile(photo);
getData(file);

The error message says that it's on the line

XFile photo = GetImage();

I tried adding more functions, adding the async, and I tried changing

File file = File(image.path);

to

File? file = File(image!.path);

Solution

  • Try to convert into Future method and await for photo.

    Future<XFile?> GetImage() async {
      print("getImage");
      final ImagePicker _picker = ImagePicker();
      final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
      return photo;
    }
    

    Now call this method with await

    XFile? photo = await GetImage(); /// convert it to async method, and this will provide nullable file