Search code examples
imageflutterdartcachingsharedpreferences

Flutter & Shared Preference : How do I save a network image to local memory?


want to save a network image into my local memory using shared_preference package.

Let's use the image below:

Link : https://user-images.githubusercontent.com/54469196/100627883-ef57f100-336a-11eb-9dac-fa3b910b8302.png

How do I do that with shared_preference?

I am looking forward to hearing from you. Thank you.


Solution

  • Your image might be too big for the following method so I'm using a smaller placeholder image from https://picsum.photos/200 that returns a random image everytime it is called. Review the following code that first checks if image is saved in Shared Preferences, if not, the code will download the image, convert the image to base64 string and save the image base64 string to Shared Preferences.

    import 'dart:async';
    import 'dart:convert';
    import 'dart:typed_data';
    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'package:shared_preferences/shared_preferences.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          theme: ThemeData.dark(),
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      @override
      State createState() => MyHomePageState();
    }
    
    class MyHomePageState extends State<MyHomePage> {
      String _base64;
      Future getImage;
    
      Future<String> _getImage() async {
        String base64;
        final SharedPreferences prefs = await SharedPreferences.getInstance();
        base64 = prefs.getString("base64Image");
        if (base64 == null) {
          final http.Response response = await http.get(
            'https://picsum.photos/200',
          );
          base64 = base64Encode(response.bodyBytes);
          prefs.setString("base64Image", base64);
        }
        return base64;
      }
    
      @override
      void initState() {
        super.initState();
        getImage = _getImage();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text('Example App')),
          body: FutureBuilder<String>(
            future: getImage,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                _base64 = snapshot.data;
                final Uint8List bytes = base64Decode(_base64);
                return ListTile(
                  leading: Image.memory(bytes),
                  title: Text(_base64),
                );
              }
              return const Center(child: CircularProgressIndicator());
            },
          ),
        );
      }
    }