Pranav Manoj
Pranav Manoj

Reputation: 69

How to update the value of a particular JSON object's value, given the key in dart

There is a local JSON object that needs to be update. The quantiy below needs to be incremented by 1.

Here's what I tried:

int quantity = jsonDecode(itemsInCart[i])['quantity'];
quantity++;
jsonDecode(itemsInCart[i])['quantity'] = jsonEncode(quantity);

But this does not work. Please help !

Upvotes: 1

Views: 1456

Answers (2)

Michael Horn
Michael Horn

Reputation: 4099

If you have a json string that you want to update, but keep as a string, you might try a utility function something like this:

String updateJson(
  String json, 
  void Function(Map<String, dynamic>) update,
) {
  final data = jsonDecode(json);
  update(data);
  return jsonEncode(data);
}

Usage:

itemsInCart[i] = updateJson(itemsInCart[i], (json) {
  if (json['quantity'] != null && json['quantity'] is int) {
    json['quantity']++;
  }
});

Edit: To explain a bit more - In order to update the json string, you need to decode that whole string (resulting in a Map), then update the property on that map, then re-encode the whole string. The updateJson function above simply abstracts away the busy work of decoding and re-encoding the string, so all you need to do is perform your updates in the callback.

Upvotes: 1

Aristidios
Aristidios

Reputation: 2331

Try wrapping it in a function like so


 Future setQuantity(int quantity) async {
    
    return jsonFile.writeAsIntSync(json.encode(quantity));
 }

then, call the function somewhere

int quantity = jsonDecode(itemsInCart[i])['quantity'];

//.... code

quantity = setBookmark(quantity)

something like that - let me know if it helped ! : )

Upvotes: 0

Related Questions