How to save to local storage using Flutter?

2 Min Read

In Flutter, you can save data to local storage using the shared_preferences package. This package provides a simple way to store key-value pairs, as well as more complex data types like lists or maps.

Here’s an example of how to save a string value to local storage:

import 'package:shared_preferences/shared_preferences.dart';

Future<void> saveStringToLocalStorage(String key, String value) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString(key, value);

And here’s how to retrieve the value:

import 'package:shared_preferences/shared_preferences.dart';

Future<String> getStringFromLocalStorage(String key) async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getString(key) ?? '';

You can use similar code to save and retrieve other data types, like integers, booleans, or lists. To save a list, for example, you can convert it to a JSON string and save it as a string, and then convert it back to a list when you retrieve it.

It’s important to note that local storage data is persisted even when the app is closed, so you can use it to store user settings, preferences, or cache data to improve app performance.

Share this Article
Leave a comment