Persisting data with local storage using the shared_preferences plugin
The shared_preferences
plugin provides one of the easiest ways to persist data in Flutter applications. It can be used to store simple key-value pairs and is suitable for storing things such as application settings and offline cache. This plugin uses underlying SharedPreferences
in Android, NSUserDefaults in iOS, and localStorage
on the web to achieve key-value persistence. You can learn more about the web’s localStorage
and its API from the official specification: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage. Using SharedPreferences, we will build a simple theme switcher, where users will be able to choose whether the theme is dark or light, which will persist the next time they come back.
Creating a theme mode service
To create a theme mode using SharedPreferences, follow these steps:
- We will start by adding it as a dependency in our application...