Save image to local storage – Flutter

In this post, you will learn to save images to local storage in Flutter. You can either use getApplicationDocumentsDirectory() or getExternalStorageDirectory() according to your need. I will give you examples of both.

How to save image in local storage in Flutter?

First, we need to add some dependencies to the project’s pubspec.yaml file. Add the following dependencies to your project’s pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.0
  path: ^1.8.2
  path_provider: ^2.0.11

Now, import the following packages.

import 'dart:core';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

I will use the following URL to get the image and save it to the local storage. Replace this URL with the URL of the image that you want to save.

String url =
      'https://cdn.pixabay.com/photo/2022/08/18/20/18/red-maple-leaves-7395624_960_720.jpg';

Now, to save this image you will use the following code.

Now, let’s understand the code in 4 simple steps –

  1. The http.get() method will create an http request to get the image. The Http response will contain the image data in its body.
  2. Use the getApplicationDocumentsDirectory() to get the Path to a directory where your application will place data.
  3. Create a File instance with the full path including the image name. To get the image name use the path.basename(url) method.
  4. Use the file.writeAsBytes(response.bodyBytes) method to save the image.

The AlertDialog is there only to show the status after the image has been saved on the device.

Output:

But, if you use getApplicationDocumentsDirectory() to save the image, then the image won’t be visible to the user. The user can’t just go to the file manager and see the image. If you want the image to be visible to the user, then use getExternalStorageDirectory() instead.

Let’s see the code.

Now, I can view the saved image.

Now, let’s see the full code.

Code using getApplicationDocumentsDirectory()

import 'package:flutter/material.dart';
import 'dart:core';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Save image to device',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String url =
      'https://cdn.pixabay.com/photo/2022/08/18/20/18/red-maple-leaves-7395624_960_720.jpg';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Save image example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            //Display the network image
            Image.network(url),
            ElevatedButton(
                onPressed: () async {
                  //Save image to file.
                  var response = await http.get(Uri.parse(url));
                  Directory directory =
                      await getApplicationDocumentsDirectory();
                  File file = new File(
                      path.join(directory.path, path.basename(url)));
                  await file.writeAsBytes(response.bodyBytes);
                  showDialog(
                    context: context, 
                    builder: (BuildContext context) => AlertDialog(
                    title: Text("Image saved Successfully!"),
                    content: Image.file(file),
                  ) );
                },
                child: Text("Save image"))
          ],
        ),
      ),
    );
  }
}

Code using getExternalStorageDirectory()

import 'package:flutter/material.dart';
import 'dart:core';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Save image to device',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String url =
      'https://cdn.pixabay.com/photo/2022/08/18/20/18/red-maple-leaves-7395624_960_720.jpg';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Save image example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            //Display the network image
            Image.network(url),
            ElevatedButton(
                onPressed: () async {
                  //Save image to file.
                  var response = await http.get(Uri.parse(url));
                  Directory? externalStorageDirectory =
                      await getExternalStorageDirectory();
                  File file = new File(
                      path.join(externalStorageDirectory!.path, path.basename(url)));
                  await file.writeAsBytes(response.bodyBytes);
                  showDialog(
                    context: context, 
                    builder: (BuildContext context) => AlertDialog(
                    title: Text("Image saved Successfully!"),
                    content: Image.file(file),
                  ) );
                },
                child: Text("Save image"))
          ],
        ),
      ),
    );
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: