DEV Community

Cover image for How to download and save image to file in Flutter
saurabh singh aswal
saurabh singh aswal

Posted on

How to download and save image to file in Flutter

“One of the simplest activities that any application can perform is saving an image that has been downloaded from the Internet in the filesystem“

Image description

Hi guyz i hope you all are well so in this article we learn how to save url image into our local device like phone. Beginning with the assumption that we already know the URL of an image, we will download it first before saving it in the gallery or to a specified location.

don’t waste your time go to the code in to do this task we will use the following dependencies:

  1. - flutter_file_dialog.
  2. - path_provider.
  3. - http.

Step 1: Create a basic layout:
Now we are going to create a very basic layout that displays an image from URL:

Image description

import 'package:flutter/material.dart';

void main() {
  runApp(const App());
}

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Save image to disk',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MainScreen(),
    );
  }
}

class MainScreen extends StatelessWidget {
  static const _url = 'https://dosomthings.com/wp-content/uploads/2022/07/dc0a7e44e96647848177c8afd4bdabdd.png';

  const MainScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Save image to disk'),
        centerTitle: true,
        backgroundColor: Color(0xFFe91e63),
        actions: [
          IconButton(
            onPressed: () {
              // We will add this method later
            },
            icon: const Icon(Icons.save,color: Colors.white,),
          ),
        ],
      ),
      body: Center(
        child: Container(
          padding: const EdgeInsets.only(
            left: 24.0,
            right: 24.0,
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(30.0),
            child: Image.network(_url),
          ),
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Give permission and set Configuration in android for Download and save image:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.saveimage">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <application>

Enter fullscreen mode Exit fullscreen mode

And we upgrade to versions compileSdkVersion & minSdkVersion like this:

android {
    //HERE..
    compileSdkVersion 33

    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
Enter fullscreen mode Exit fullscreen mode

Step 3: Download and save image from the URL to a file:
The last step is to save the image to disk copy and paste.

import 'dart:math';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter_file_dialog/flutter_file_dialog.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(const App());
}

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Save image to disk',
      home: MainScreen(),
    );
  }
}

class MainScreen extends StatelessWidget {
  static const _url = 'https://dosomthings.com/wp-content/uploads/2023/07/How-to-download-and-save-image-to-file-in-FlutterDosomthings.com_-1024x576.png';
  var random = Random();


  Future<void> _saveImage(BuildContext context) async {
    final scaffoldMessenger = ScaffoldMessenger.of(context);
    late String message;

    try {
      // Download image
      final http.Response response = await http.get(
          Uri.parse(_url));

      // Get temporary directory
      final dir = await getTemporaryDirectory();

      // Create an image name
      var filename = '${dir.path}/SaveImage${random.nextInt(100)}.png';

      // Save to filesystem
      final file = File(filename);
      await file.writeAsBytes(response.bodyBytes);

      // Ask the user to save it
      final params = SaveFileDialogParams(sourceFilePath: file.path);
      final finalPath = await FlutterFileDialog.saveFile(params: params);

      if (finalPath != null) {
        message = 'Image saved to disk';
      }
    } catch (e) {
      message = e.toString();
      scaffoldMessenger.showSnackBar(SnackBar(
        content: Text(
          message,
          style:  TextStyle(
            fontSize: 12,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: Color(0xFFe91e63),
      ));
    }

    if (message != null) {

      scaffoldMessenger.showSnackBar(SnackBar(
        content: Text(
          message,
          style:  TextStyle(
            fontSize: 12,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: Color(0xFFe91e63),
      ));

    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Save image to disk'),
        centerTitle: true,
        backgroundColor: Color(0xFFe91e63),
        actions: [
          IconButton(
            onPressed: () {
              _saveImage(context);
            },
            icon: const Icon(Icons.save,color: Colors.white,),
          ),
        ],
      ),
      body: Center(
        child: Container(
          padding: const EdgeInsets.only(
            left: 24.0,
            right: 24.0,
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(30.0),
            child: Image.network(_url),
          ),
        ),
      ),
    );
  }
}



Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Conclusion:
In this article, we have learned how to download and save an image to a file in Flutter. By following these steps, you can incorporate image downloading and saving functionality into your Flutter applications, opening up possibilities for offline image viewing and user-driven image saving features.
I hope now you understand how to download image. seriously you don’t believe when i don’t know how to download image then i try find the solution in many youtube channel and article but no one can explains briefly how to do this task. but finally i got. So now this is your turn do code and enjoy it.

If you you stuck in any case or you go too deep in this topic so you can checkout my new post in this topic 👇👇👇

How to download and save image to file in Flutter

❤️❤️ Thanks for reading this article ❤️❤️

If I got something wrong? Let me know in the comments. I would love to improve 🥰🥰🥰.

Clap 👏👏👏 If this article helps you.

if you like our work so please follow us on this Dosomthings

Our New and Attractive articles:

StreamBuilder VS FutureBuilder: Difference Between StreamBuilder and FutureBuilder In Flutter.

Tinder swipe card: How to implement tinder swipe card in a flutter.

Time Delay in Flutter: How to Run Code After Time Delay in Flutter App.

Top comments (0)