Junior
What is the feature of using SharedPreferences in Flutter?
sobes.tech AI
Answer from AI
SharedPreferences provides a simple API for storing small amounts of data (primitive types: int, double, bool, String, List<String>) as key-value pairs. Data is stored asynchronously. This is suitable for storing user settings, flags, and other non-critical information.
Features:
- Ease of use: The API is lightweight and intuitive.
- Asynchronous operations: All read and write operations are asynchronous, preventing UI thread blocking.
- Limited set of types: Supports only primitive types and list of strings.
- Not suitable for large volumes or complex data: Inefficient for storing large data structures or many records.
- Platform dependence: Implementation is based on native data storage mechanisms (e.g.,
NSUserDefaultson iOS,SharedPreferenceson Android). - Not secure for confidential information: Data is stored in plain text, not suitable for passwords or sensitive data.
- Requires
awaitfor access: Getting an instance ofSharedPreferencesand performing read/write operations require usingawait.
Example usage:
// Getting an instance of SharedPreferences
final prefs = await SharedPreferences.getInstance();
// Writing data
await prefs.setInt('counter', 10);
await prefs.setBool('isDarkMode', true);
await prefs.setString('username', 'FlutterDev');
await prefs.setStringList('items', ['apple', 'banana']);
// Reading data
final counter = prefs.getInt('counter') ?? 0; // Using ?? for default value
final isDarkMode = prefs.getBool('isDarkMode') ?? false;
final username = prefs.getString('username');
final items = prefs.getStringList('items') ?? [];
// Removing data
await prefs.remove('username');
await prefs.clear(); // Removes all data