Flutter SEMBAST database: insert new item in a list of an object

Viewed 587

Want to insert a new item in a list of an object in SEMBAST database,

object JSON format:

{
  "id": "1",
  "name": "Apple",
  "isSweet": true,
  "leaves": [
    {
      "id": "1",
      "name": "leaveOne"
    },
    {
      "id": "2",
      "name": "leaveTwo"
    },
  ]
}

want to insert leave three, with "id": 3, "name": leaveThree, also want to update leave name, how to add new leave, and change leave name?

here is the fruit and leave model:

class Fruit {
  final String id;
  final String name;
  final bool isSweet;
  final List<Leaves> leaves;

  Fruit({this.id, this.name, this.isSweet, this.leaves});

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'isSweet': isSweet,
      'leaves': leaves.map((leave) => leave.toMap()).toList(growable: false)
    };
  }

  static Fruit fromMap(Map<String, dynamic> map) {
    return Fruit(
      id: map['id'],
      name: map['name'],
      isSweet: map['isSweet'],
      leaves: map['leaves'].map((mapping) => Leaves.fromMap(mapping)).toList().cast<Leaves>(),
    );
  }
}

class Leaves {
  final String id;
  final String name;

  Leaves({this.id, this.name});

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
    };
  }

  static Leaves fromMap(Map<String, dynamic> map) {
    return Leaves(
      id: map['id'],
      name: map['name'],
    );
  }
}

how can I insert new leave and update leave?

1 Answers

If I understand correctly, since leaves is a nested list, you have to update the field entirely (i.e. you have to manipulate/clone/modify the leaves list yourself and set it in your Fruit object). There is no arrayUnion/arrayRemove operation like in firestore.

Related