Home > other >  Flutter 'File' can't be assigned to 'XFile'
Flutter 'File' can't be assigned to 'XFile'

Time:11-29

I have a function to save network image to local cache files, but I have a trouble when store the list file that I downloaded to List<XFile>. Here is my download function:

List<XFile>? imageFileList = [];
Future<File> downloadImage(url, filename) async {
    var httpClient = HttpClient();
    try {
      var request = await httpClient.getUrl(Uri.parse(url));
      var response = await request.close();
      var bytes = await consolidateHttpClientResponseBytes(response);
      final dir = await getTemporaryDirectory();
      File file = File('${dir.path}/$filename');
      await file.writeAsBytes(bytes);
      print('downloaded file path = ${file.path}');
      return file;
    } catch (error) {
      print('download error');
      return File('');
    }
  }

is there any way so I can save the file to imageFileList as :

imageFileList!.add(file);

CodePudding user response:

Change your list type:

from this:

List<XFile>? imageFileList = [];

to this:

List<File>? imageFileList = [];

final ImagePicker _picker = ImagePicker();

 getImage() async {
   var images = await _picker.pickMultiImage();
   images!.forEach((image) {
     setState(() {
       _imageFileList!.add(File(image.path));
     });
   });
 }
  • Related