How To Store Flutter App Data On Your Device

Introduction Link to heading

In this article, I’ll show you how to store Flutter app data on your device with the plugin shared_preferences. It’s the default solution when you want to store some data!

Shared Preferences is a useful tool for persisting small amounts of data, such as user settings. It’s a key-value store similar to a Dictionary in Dart. The API is easy to learn, with getter and setter methods for various types like Int, Double, Bool, String, and StringList. Let’s learn how to store Flutter app data on your device with it!

It’s available for all major platforms like Android, iOS, macOS, Windows, Linux, and web. Under the hood, it uses the native SDKs provided by the operating system.

Reading and writing primitive data Link to heading

Shared Preferences stores the data on the local hard drive. When you relaunch your app, you can load the data from disk and continue working as before.

Here is a code example showing how to read and write data with the Shared Preferences package:

Working with complex objects Link to heading

To store complex data objects, we use the following approach:

  1. Implement your custom class

  2. Add a fromJson factory constructor that constructs an object from a Map<String, dynamic>

  3. Add to toJson method that returns a Map<String, dynamic> from your object

  4. Save it with await prefs.setString("key", jsonEncode(myObject.toJson()))

  5. Load it with CustomClass.fromJson(jsonDecode(prefs.getString(”key”)))

Here is a short example of such a class:

With this approach, you can store any complex object with the Shared Preferences plugin.

Testing Link to heading

When you have tests that rely on Shared Preferences, you can use a mock implementation. The following code shows how to set values for testing:

Dart

final Map<String, Object> values = <String, Object>{'counter': 1};
SharedPreferences.setMockInitialValues(values);

In this test mode, Shared Preferences will not store any data on persistent storage. All operations only work in memory.

Conclusion Link to heading

In this article, you learned how to store Flutter app data on your device with the plugin shared_preferences. It works well with primitive and complex data types and has great testing support.



Choose the Best Data Storage Solution for Your Flutter App Link to heading

Whether you need local storage, secure storage, or a cloud database, Flutter has you covered. Here is a guide to choose the best data storage solution for your Flutter app.

How to Use the Scaffold Widget in a Flutter Application Link to heading

Here is how to use the Scaffold widget in a Flutter application to create a consistent app skeleton in no time!

How To Create Beautiful Charts And Graphs In Your Flutter Application Link to heading

Learn how to create beautiful charts and graphs in your Flutter application to create dashboards or visualize statistic evaluations.