Advertisement
Beginner Flutter, Local Data Storage with SharedPreferences

How do you actually properly read and write different basic primitive data types, such as a String, an int, and a bool, using the shared_preferences package's own available methods?

Short answer

The shared_preferences package provides dedicated genuinely type specific methods for each basic supported primitive data type, including setString and getString for text values, setInt and getInt for whole numbers, and setBool and getBool for boolean true or false values, and…

Save Flutter mock interview
Advertisement
AModel answer
The shared_preferences package provides dedicated genuinely type specific methods for each basic supported primitive data type, including setString and getString for text values, setInt and getInt for whole numbers, and setBool and getBool for boolean true or false values, and each individual stored value is genuinely associated with its own particular unique specific string key, letting you reliably retrieve that exact same stored value again later simply by properly providing that exact same matching key string.
await prefs.setString('username', 'alex123');
await prefs.setInt('loginCount', 5);
final username = prefs.getString('username');
Real-world example
A login screen stores a user's own chosen username using setString and properly tracks how many times they have already genuinely logged in using setInt, correctly retrieving both of those separately stored values again the very next time that same particular user actually reopens the app.
Likely follow-ups
  • What genuinely happens if you try to actually read a specific key that was never actually properly saved in the first place?
  • Can SharedPreferences genuinely store a more complex object such as a List or a Map directly?
Related topics