Yes, Flutter has a built-in mechanism for storing key-value pairs to local storage using the shared_preferences package. Here are the steps to save and retrieve data using shared_preferences:
- Add the shared_preferences package to your pubspec.yaml file:
dependencies:
shared_preferences: ^2.0.8
- Import the shared_preferences package in your Dart code:
import 'package:shared_preferences/shared_preferences.dart';
- To save a value to local storage, create an instance of SharedPreferences and call the setString, setBool, or setInt method, depending on the type of data you want to save:
Future<void> _saveData(String key, String value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(key, value);
}
- To retrieve a value from local storage, call the getString, getBool, or getInt method, depending on the type of data you want to retrieve:
Future<String?> _loadData(String key) async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(key);
}
You can call these methods from anywhere in your Flutter app to save and retrieve data to/from local storage. Note that the data will persist even if the app is closed and reopened.
If you need to store more complex data structures, such as lists or maps, you can serialize them to JSON format and store the JSON string as a value in shared preferences. You can then deserialize the JSON string back into a data structure when you retrieve it.
To know more, join our Flutter App Development Course today.