Home > Net >  how to add a list of an item to cart using shared preferences [flutter]
how to add a list of an item to cart using shared preferences [flutter]

Time:02-19

so currently i'm learning about flutter & dart.

so, i was trying to make a cart system using shared_preferences package, but i still don't know how.

i want to have a list of an item in cart, here's what pretty much i'm trying to achieve using shared_preferences

[{"id":109,"itemCount":"1","price":1269945,"image":"image.jpg"}, {"id":200,"itemCount":"1","price":2090424,"image":"image.jpg"}]

so if anyone know how to do it, or have a suggestion on how to do it without shared_preferences, please answer this questions.

Thanks in advance by the way.

CodePudding user response:

What you need to achieve that is a Map, since you need to map the item ID to the count (I'd really reccomend to remove the price and to fetch it by ID, it would give an updated and live result). Shared Preferences does not support maps as you can see from the documentation, but it supports strings. If you need a solution which isn't great from a performance side but really easy to implement you can use the following snippet:

[...]
 
const cartKey = 'cart';
final prefs = await SharedPreferences.getInstance();

final myItems = [
  {
    "id": 109,
    "itemCount": "1",
    "price": 1269945,
    "image": "image.jpg",
  },
  {
    "id": 200,
    "itemCount": "1",
    "price": 2090424,
    "image": "image.jpg",
  },
];

final myItemsAsJsonString = json.encode(myItems);

await prefs.setString(cartKey, myItemsAsJsonString);

[...]

When your user re-opens the app:

[...]

final myItemsAsJsonString = prefs.getString(cartKey);

final myItems = json.decode(myItemsAsJsonString);

[...]

CodePudding user response:

Instead of using shared_preferences, I suggest you to use a State Manager like Provider/RiverPod, it is designed also for this kind of situations. Shared Preferences is designed to be used for storing small informations.

RiverPod package: RiverPod

Provider package: Provider

Small guide for Provider

  • Related