skip to Main Content

I am building a home page where the user can replace default image. Whenever the user opens the application second time, I want that image user picked previously to show up and not the default image. How do I do this in dart/flutter?

I tried doing research, but was not able to find helpful articles.

3

Answers


  1. You will need to persist between runs which image the user has selected. To do so, you can use the shared_preferences package.

    When the user selects an image, set the image and also set a key using shared_preferences indicating which image was selected. The value of the key will likely be a string, and it could be — for example — a URL, a path on the local filesystem, or a path in the assets bundle. How exactly you choose to represent the user’s selection is up to you and depends on your specific use case.

    And, when your app loads, retrieve that key from shared_preferences and use the value to load the correct image for display.

    Login or Signup to reply.
  2. For this, it is necessary to save the last remaining image using the internal memory.

    For example

    Getx Storage

    Hive

    Remember the image sequence number every time the image is changed. This will help you show the images from the index immediately when the program is closed and reopened.

    I gave a brief explanation here as general information.

    Login or Signup to reply.
  3. You can save the image as files of specific path(getting the directory from path_provider, and then look for file at the same path the next time.
    Also you can use image_picker to select the image on iOS and Android.

    import 'package:flutter/material.dart';
    import 'package:path_provider/path_provider.dart';
    import 'package:image_picker/image_picker.dart';
    import 'dart:io';
    
    late Directory dir;
    late File file;
    
    final imagePicker = ImagePicker();
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      dir = await getApplicationDocumentsDirectory();
      file = File("${dir.path}/userImage1");
    
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          home: Scaffold(
            body: Center(
              child: SizedBox(
                height: 300,
                width: 300,
                child: MyWidget(),
              ),
            ),
          ),
        );
      }
    }
    
    class MyWidget extends StatefulWidget {
      const MyWidget({super.key});
    
      @override
      State<MyWidget> createState() => _MyWidgetState();
    }
    
    class _MyWidgetState extends State<MyWidget> {
      @override
      Widget build(BuildContext context) {
        if (!file.existsSync()) {
          return Column(
            children: [
              Container(
                color: Colors.purple,
              ),
              ElevatedButton(
                onPressed: () async {
                  final imgfile = await imagePicker.pickImage(source: ImageSource.gallery);
                  if (imgfile != null) {
                    await imgfile.saveTo(file.path);
                    //clear the cache image of that path, or else the image won't change
                    FileImage(file).evict();
                  }
                  setState(() {});
                },
                child: const Text("Pick Image"),
              ),
            ],
          );
        } else {
          return Column(
            children: [
              Image.file(key: UniqueKey(), file),
              ElevatedButton(
                  onPressed: () async {
                    final imgfile = await imagePicker.pickImage(source: ImageSource.gallery);
                    if (imgfile != null) {
                      await imgfile.saveTo(file.path);
                      //clear the cache image of that path, or else the image won't change
                      FileImage(file).evict();
                    }
                    setState(() {});
                  },
                  child: const Text("Pick Image")),
            ],
          );
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search