Home > OS >  What is an efficient way of keeping some state data when the page is reloaded in flutter web?
What is an efficient way of keeping some state data when the page is reloaded in flutter web?

Time:11-13

I'm kinda new to flutter web and I wanted to know what is a good, clean way of handling this problem. So consider I have a shop app and the customer has added some products to their cart, this data is saved in my state (I use Riverpod but I reckon it doesn't mater what state management is used). When the user reloads the page, the cart will be empty as expected (since all the states will be reloaded). I wanted to know what is a good way of handling this problem? Should I use cookies, shared preferences, hive, or something else? I just wanted to know what a more experienced developer would recommend. Thank you in advance for any help you provide.

CodePudding user response:

Cookies are usually created by the server, while SharedPreferences is something client specific.

From an architecture point of view, you probably want the server to know about shopping carts (e.g. when the user logs in on a different device; to indicate that product might be sold soon; ... ). This however adds one more layer of complexity and I would only recommend this if you have a good reason for the server to know about it.

The simple straightforward path I would take for a private project is to save it in SharedPreferences. You can write a toJson and a fromJson function and save/load your cart as stringified JSON.

You can later still decide to move that logic to the server over the course of your application if there turns out to be a business need for it.

  • Related