Junior — Middle
Can you explain what SharedPreferences is and how it is used to store data in Android applications?
sobes.tech AI
Answer from AI
SharedPreferences in Android is a mechanism for storing simple data in key-value pairs. It is commonly used for saving application settings, flags, or small data that needs to persist between app launches.
Data is stored in an XML file and is accessible only to your application.
Example of usage in Flutter with the shared_preferences package:
import 'package:shared_preferences/shared_preferences.dart';
// Saving a value
Future<void> saveUsername(String username) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('username', username);
}
// Reading a value
Future<String?> getUsername() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString('username');
}
Thus, SharedPreferences is suitable for storing small and simple data that does not require complex structure.