Harnessing the power of localStorage API in Flutter Web Apps

Tirth Patel
3 min readSep 8, 2019
Photo by Annie Spratt on Unsplash

Hey Everyone! Today we’re going to explore localStoage API of dart:html library by creating a Flutter Web App which persists value of brightness property of ThemeData 🌞 🌃

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.

🔌 Prerequisites

🎹 Coding

Initial Setup
Initial Setup
  • 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.
After Overriding initState
After Overriding initState
  • 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.
After adding IconButton in appBar
After adding IconButton in appBar

That’s it for this one. Thank you for reading this 💙

You can find complete source code of this app in this repository.

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.

--

--