Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 556
L.Goyal Avatar asked Aug 11 '20 07:08

L.Goyal


People also ask

How do I get a Flutter Uint8List from a network image?

dart' as http; import 'package:path/path. dart' as path; import 'package:path_provider/path_provider. dart'; Future<File> getFileFromNetworkImage(String imageUrl) async { var response = await http. get(imageUrl); final documentDirectory = await getApplicationDocumentsDirectory(); String fileName = DateTime.

How do I convert a network image to a File in Flutter?

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.


Video Answer


1 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;
  }
like image 69
Taym95 Avatar answered Sep 23 '22 13:09

Taym95