Ask Your Question
2

How to save an image from the internet to a local directory using Flutter?

asked 2023-05-23 03:56:05 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-23 04:02:01 +0000

devzero gravatar image

You can save an image from the internet to a local directory using Flutter by using the dio package to download the image and the path_provider package to get the local app directory. Here's an example of how to do it:

First, add the dio and path_provider packages to your pubspec.yaml file:

dependencies:
  dio: ^4.0.0
  path_provider: ^2.0.1

Then import them in your Dart file:

import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

Next, use the following code to download the image and save it to a local directory:

void saveImage(String imageUrl) async {
  try {
    Dio dio = Dio();
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String savePath = appDocDir.path + "/image.jpg";
    await dio.download(imageUrl, savePath);
    print("Image saved to local directory");
  } catch (e) {
    print(e.toString());
  }
}

Replace imageUrl with the URL of the image you want to download. The getApplicationDocumentsDirectory() method gets the directory where your app can store files. savePath is the path to the file where the image will be saved. Finally, the dio.download() method downloads the image from the URL and saves it to the local directory.

Note that you need to add the android.permission.WRITE_EXTERNAL_STORAGE permission to your AndroidManifest.xml file if you want to save the image to external storage.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-23 03:56:05 +0000

Seen: 13 times

Last updated: May 23 '23