Flutter - Network Image to File

Viewed 9978

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.

2 Answers

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('https://example.com/xyz.jpg');

    final documentDirectory = await getApplicationDocumentsDirectory();

    final file = File(join(documentDirectory.path, 'imagetest.png'));

    file.writeAsBytesSync(response.bodyBytes);

    return file;
  }
import 'dart:io';   
import 'package:dio/dio.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';


Future<File> getImage({required String url}) async {
  /// Get Image from server
  final Response res = await Dio().get<List<int>>(
    url,
    options: Options(
        responseType: ResponseType.bytes,
      ),
    );

    /// Get App local storage
    final Directory appDir = await getApplicationDocumentsDirectory();

    /// Generate Image Name
    final String imageName = url.split('/').last;

    /// Create Empty File in app dir & fill with new image
    final File file = File(join(appDir.path, imageName));

    file.writeAsBytesSync(res.data as List<int>);

    return file;
}
Related