Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter save a network image to local directory

Tags:

In Flutter how to save an image from network to the local directory.

I am new to encoding and decoding images. Can anyone point me in the right direction?

like image 951
Aritra Dattagupta Avatar asked Mar 23 '18 17:03

Aritra Dattagupta


People also ask

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

Response responseData = await http. get(imageUrl); Uint8List imageBytes = responseData. bodyBytes; this works on device and web too, hope it can help.

How to save the network image in flutter?

Follow this url flutter save network image. To save the network image in local system you need to use ImagePickerSave dart plugin. Add the dart plugin in pub.yaml file: image_picker_saver: ^0.1.0 and call below code to save the image. URL is the image URL of network image

How to read and write to a file in flutter?

Flutter has a built in type called File which will allow us to read and write to a file locally. To make our lives easier we do need to add a package, the path_provider package, which you can find here. The path_provider package is used for "finding commonly used locations on the filesystem".

How to save the network image in local system using Dart?

To save the network image in local system you need to use ImagePickerSave dart plugin. Add the dart plugin in pub.yaml file: image_picker_saver: ^0.1.0 and call below code to save the image. URL is the image URL of network image

How do I use the path_provider package in flutter?

The path_provider package is used for "finding commonly used locations on the filesystem". Before we get started, be sure to add the following to your pubspec.yaml under dependencies: Once you have added that to your pubspec, you can run flutter pub get, after that has completed remember to import the following where ever it is required:


1 Answers

If all you want is to save an image (example: a .png) to the device, you can easily achieve this with a simple get (http/http.dart) and a File (dart:io).

To do so, you can base yourself in the example below:

var response = await http.get(imgUrl);
Directory documentDirectory = await getApplicationDocumentsDirectory();
File file = new File(join(documentDirectory.path, 'imagetest.png'));
file.writeAsBytesSync(response.bodyBytes); // This is a sync operation on a real 
                                           // app you'd probably prefer to use writeAsByte and handle its Future

Note that in the case above I’ve used the ‘path_provider’ package from the dart pub. In overall you would have imported at least these items:

import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
like image 154
LuDanin Avatar answered Sep 20 '22 18:09

LuDanin