'Saving user data when application closes in Flutter

I want to automatically save the username and password of password when he connects to the login page of my app, to then autofill the username and password field with the data in the next connection.

To do this I use a class which I called ContextManager where I store data I need to use in my app. I also use SharedPreferences.

Here is the code which is executed when the user log in to the app :

if (ContextManager.isConnected == false) {
      return 'Le nom d\'utilisateur ou le mot de passe est incorrect';
    } else {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('email', data.name);
      prefs.setString('password', data.password);
      ContextManager.savedEmail = prefs.getString('email').toString();
      ContextManager.savedPassword = prefs.getString('password').toString();
      return null;
    }

And then in the build of my LoginPage widget I return a FlutterLogin widget (from the flutter_login package) with the value ContextManager.savedPassword for his savedPassword attribute, and ContextManager.SavedEmail for his savedEmail attribute.

It works when the app is running and I'm logging out while still in the app, the data is stored and autofilled correctly, but when I'm stopping the app and running it back all data is gone.

How could I permanently stored the data and simply retrieve it in the app at any moment ?

Thanks.



Solution 1:[1]

From my experience, I know three different packages to store data between app restart.

The first I use is the package sqflite, which, as the name suggests, includes a full SQLite database (but I don't know if that fits your definition of "simply retrieve it").

A simpler tool is the shared_preferences package, that allows you to store data as a key-value pairs(stored somewhere in a file unreachable by the user, if I'm correct).

The last one that I know of, that I used for a desktop app, is the ini package, that lets you create a configuration file like the .ini files often found in desktop applications. It's less user-friendly than the other two, but it allows you to choose where to put the file, and lets the user access that file if needed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 il_boga