Junior — Middle
What is the purpose of data storage mechanism using SharedPreferences in mobile applications?
sobes.tech AI
Answer from AI
SharedPreferences is used in mobile applications to store small amounts of data as key-value pairs. It is convenient for saving user settings, flags, tokens, and other information that needs to persist between app launches. Data is stored in persistent storage and accessible on next app start.
Example usage in Flutter:
import 'package:shared_preferences/shared_preferences.dart';
// Save value
Future<void> saveUsername(String username) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('username', username);
}
// Retrieve value
Future<String?> getUsername() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString('username');
}