Home > Software engineering >  How to convert type String to type File in Flutter
How to convert type String to type File in Flutter

Time:08-24

I am running a project with flutter-web

This time is first time doing project with flutter-web. and now i just knew that flutter web doesn't supports Dart:io

So i am trying to use dart.html and... it is quite different compare to dart:io

uploadImage(ReservationPvd reservationPvd) async {
    final XFile? photo = await ImagePicker().pickImage(source: ImageSource.gallery);
    File image = File(photo!.path);
    MultipartFile imageFile = await MultipartFile.fromFile(photo.path);
    reservationPvd.updateInfo('image', image);
    reservationPvd.updateInfo('imageFile', imageFile);
  }

this following code is the code that i've used in my other project with flutter. and I need to save this File to Type File and MultipartFile

File image = File(photo!.path);

and this following code gives an error message, and it says

The argument type 'String' can't be assigned to the parameter type 'List<Object>'

i have googled for a 3 days but i really can't solve this problem...

does anyone knows how to upload fine ways to upload in flutter-web?

CodePudding user response:

I suspect your File class may be imported from the wrong dependency. It should use File from dart:io like so:

import 'dart:io';

And it's likely you're currently using dart:html:

import 'dart:html';

Auto import suggests dart:html over dart:io for me as well, so this is the most likely cause I think.

CodePudding user response:

to get around dart io not supported in web after you pick the image instead of File(file.path) you say file.readAsBytes(); the you store the output of file.readAsBytes() in a Uint8List variable. when you want to display the images you use MemoryImage() provided in flutter

CodePudding user response:

I have flutter-web project and it use MultipartFile.fromBytes not MultipartFile.fromFile. Because in flutter-web you can't get File from path. Try this:

uploadImage(ReservationPvd reservationPvd) async {
    final XFile? photo = await ImagePicker().pickImage(source: ImageSource.gallery);

    MultipartFile imageFile = MultipartFile.fromBytes(await photo!.readAsBytes());
    
    reservationPvd.updateInfo('image', image);
    reservationPvd.updateInfo('imageFile', imageFile);
  }
  • Related