In localStorage, data is stored in key-value pair where both key & value only supports String type of data. It is incredibly easy to use API. Data is persisted even after browser is closed and it works on same-origin policy. Unlike cookies, there is no expiration date for data stored in localStorage & it offers more storage (5 MB). Stored data can be cleared programmatically using Dart or by navigating to Browser > Developer Tools > Application > Storage > LocalStorage.
There are some important things which you should keep in mind while using localStorage:
- Never store Sensitive Information.
- Read/Write operations are Synchronous.
- Only String data is supported.
Now let’s get started with some code.
- Create a new Flutter web project using IDE wizard.
- Navigate to lib/main.dart file and remove everything.
- Create a StatefulWidget with MaterialApp & Scaffold in it.
- Set appBar and body properties of Scaffold by adding a AppBar and a Text respectively.
- Now add a new data-member named _appTheme & initialise it with Brightness.light in _MyAppState, which will store brightness (theme).
- Override initState method to fetch current value of brightness from localStorage.
- If value of (current theme) window.localStorage[‘theme’] is Dark then assign _appTheme with Brightness.Dark, otherwise assign with Brightness.Light.
- If key named theme doesn’t exist in localStorage then we’ll write window.localStorage[‘theme’] = ‘Light’; to create a new entry in localStorage.
- Lastly add brightness: _appTheme, property in ThemeData to assign current theme.
- Add a child widget IconButton in actions property of AppBar.
- Set a callback in onPressed property of IconButton.
- In callback we’ll get current theme and store the same in currentTheme variable. If the value of variable currentTheme is Dark then change it Light, and vice versa & store the new value in newTheme variable. Assign newTheme to window.localStorage[‘theme’], to update theme in localStorage. Finally, call setState to update _appTheme state.
That’s it for this one. Thank you for reading this 💙
You can find complete source code of this app in this repository.
Example code for my write-up "Harnessing the power of localStorage API in Flutter Web App". It uses window.localStorage…
If you find this post useful, press👏 button as many times as you can and share this post with others. You can leave your feedback/suggestion in comments 💬 below.
For any other issues feel free to reach out to me via Twitter.