Junior
What is SharedPreferences and how to use it?
sobes.tech AI
Answer from AI
SharedPreferences is a simple mechanism for storing small amounts of data in key-value pairs. It is ideal for saving user settings or small flags.
Usage:
-
Adding dependency: In the
pubspec.yamlfile, add:dependencies: flutter: sdk: flutter shared_preferences: ^2.2.0 # Use the latest versionand run
flutter pub get. -
Import:
import 'package:shared_preferences/shared_preferences.dart'; -
Getting an instance:
// Asynchronous operation SharedPreferences prefs = await SharedPreferences.getInstance(); -
Writing data:
// Write a string prefs.setString('username', 'Alice'); // Write an integer prefs.setInt('age', 30); // Write a double prefs.setDouble('salary', 50000.50); // Write a boolean prefs.setBool('darkMode', true); // Write a list of strings prefs.setStringList('items', ['item1', 'item2']);All write methods return
Future<bool>, indicating success. -
Reading data:
// Read a string String? username = prefs.getString('username'); // Returns null if key not found // Read an integer int? age = prefs.getInt('age'); // Read a double double? salary = prefs.getDouble('salary'); // Read a boolean bool? darkMode = prefs.getBool('darkMode'); // Read a list of strings List<String>? items = prefs.getStringList('items'); -
Deleting data:
// Remove by key prefs.remove('username'); // Returns Future<bool> // Clear all data prefs.clear(); // Returns Future<bool>
Limitations:
- Not suitable for storing large amounts of data or complex structures.
- Data is stored in plain text (though at the app level), not suitable for sensitive information.
- Works with basic data types. For objects, serialization/deserialization (e.g., with JSON) is required.