The shared_preferences plugin
- Saving data
-
Write formatted data, like JSON, to a file.
-
Use a library or plugin to write simple data to a shared location
-
Use a SQLite database.
- Why save small bits of data?
- The shared_preferences plugin
There are three primary ways to save data to your device:
Writing data to a file is simple, but it requires you to handle reading and writing data
in the correct format and order.
You can also use a library or plugin to write simple data to a shared location
managed by the platform, like iOS and Android. This is what you’ll do in this chapter.
For more complex data, you can save the information to a local database. You’ll learn
more about that in future chapters.
There are many reasons to save small bits of data. For example, you could save the
user ID when the user has logged in — or if the user has logged in at all. You could
also save the search history to consult later.
Note that this simple data saved to a shared location is lost when the user uninstalls
the app or clear the app data and cache.
shared_preferences is a Flutter plugin that allows you to save data in a key-value
format so you can easily retrieve it later. Behind the scenes, it uses the aptly named
SharedPreferences on Android and the similar UserDefaults on iOS.
For the app 4, you’ll learn to use the plugin by saving the Best Score and for the app 8, by saving the
favorite movies.
One of the great things about this plugin is that it doesn’t require any setup or
configuration. Just create an instance of the plugin and you’re ready to fetch and save
data.
Note
The shared_preferences plugin gives you a quick way to persist and
retrieve data, but it only supports saving simple properties like strings,
numbers, and boolean values.
In later chapters, you’ll learn about alternatives that you can use when you
want to save complex data.
Be aware that shared_preferences is not a good fit to store sensitive data. To
store passwords or access tokens, check out the Android Keystore for Android
and Keychain Services for iOS, or consider using the flutter_secure_storage
plugin.