There could be a time where you need to just save a simple value, like a boolean, a string or even an integer. This very easy task can result in useless complications if you save it into a file or into a database. Small & easy tasks should let you use easy and quick solutions. Let’s introduce shared_preferences then!
Android and iOS have different ways to perma-save small data, Android has
SharedPreferences class, which represents an app-managed XML file (ore more files) with key-value elements, also they can be shared across other applications.
UserDefaults is iOS way to store simple data, representing a simple synchronous database with cache features.
Flutter doesen’t have a built-in way to access these interfaces but a plugin directly created by Flutter Developers comes on our aid: shared_preferences. This simple plugin will let you use SharedPreferences and UserDefaults without worrying about the platform your app is running on! Let’s see a simple example to know better how to use it!
Here we have a simple app with a textbox, 2 buttons and a text. We want to save the input witha button and show it with the other button.
Let’s give our ‘Save’ button some action by populating its onPressed method:
Our saveText method can be now populated with shared_preferences methods.
First thing first, we need to istantiate our class, then just wait that it writes our data with an async method: setString. SharedPreference object have different methods for different type of data:
setBool… even setStringList. We also wish to print if the data is saved correctly, any “set” method return a Future<bool> so we know if everything goes well. Let’s give our text as key “OurText”.
Our code will become:
Writing something on our TextField, then clicking “save” will result then in:
Now we should show our text. Time to work on ‘Show’ button:
Like saving we instantiate SharedPreferences then get our string with… getString (applause…). SharedPreferences.getInstance() is a future so we’ll need to get our String in a async method:
And there we have:
Our text now is saved on SharedPreferences and UserDefaults, so even if we kill the app we can still show it without writing it down.