Search code examples
flutterdartflutter-dependencies

Flutter - Network Image to File


I have an Image URL like "https://example.com/xyz.jpg". Now I want to put the image in a File type variable;

Something along these lines:

File f = File("https://example.com/xyz.jpg");

The whole point is to get the image from the given URL and save it as a File variable. How can I do so? I searched for many solutions on the internet but there was no straightforward way to do so.

PS: I could have missed something where the question was similarly answered so please let me know the link where I can find it.

Edit: I am using the File type variable to pass it in the share function. This is the library that I am using.

Here is my current on share button click code

if (file != null) {
   ShareExtend.share(file.path, "image",
   sharePanelTitle: "share image title",
   subject: "share image subject");
}

Thanks for your help.


Solution

  • You need to download image and create an empty file then fill the file with image data:

    
    import 'dart:io';
    import 'package:http/http.dart' as http;
    import 'package:path/path.dart';
    import 'package:path_provider/path_provider.dart';
    
    Future<File> _fileFromImageUrl() async {
        final response = await http.get(Uri.parse('https://example.com/xyz.jpg)');
    
        final documentDirectory = await getApplicationDocumentsDirectory();
    
        final file = File(join(documentDirectory.path, 'imagetest.png'));
    
        file.writeAsBytesSync(response.bodyBytes);
    
        return file;
      }