RitikaDesai
RitikaDesai

Reputation: 55

RealTime Database with Flutter overwrites data instead of adding it to the existing nodes

I am using flutter with Firebase Realtime Database. As shown in the code, each user can create his lists and add tasks to it. However, every time I try to add a new task to the same list it overwrites the existing data instead of appending to it. Can someone please help me out.

This is the ToDo model

class Todo {
  String group;
  String subject;
  bool completed;
  String userId;

  Todo(this.userId, this.group, this.subject, this.completed);

  Todo.fromSnapshot(DataSnapshot snapshot)
      : group = snapshot.value["group"],
        userId = snapshot.value["userId"],
        subject = snapshot.value["subject"],
        completed = snapshot.value["completed"];

  toJson() {
    return {
      userId: {
        "lists": [
          {
            "groupname": group,
            "tasks": [
              {"name": subject, "done": completed},
            ]
          },
        ]
      }
    };
  }
}

This is the function to add to the database

addNewTodo(String groupn, String taskn) {
    if (groupn.length > 0 && taskn.length > 0) {
      Todo todo =
          new Todo(widget.userId, groupn.toString(), taskn.toString(), false);
      _database.reference().child("Todo").set(todo.toJson());
    }
  }

groupn & taskn are the variables inputted by the user.

Upvotes: 0

Views: 593

Answers (1)

Arvind
Arvind

Reputation: 724

Use push() to append data under your child.

You'd need to remove current data under "Todo" child for sanity, since your structure of data would change to something of this format:

Todo
  |-> "UniqueID1"
  |     |-> Todo Details (JSON)
  |
  |-> "UniqueID2"
  |     |-> Todo Details (JSON)
  |
  |-> ...

UniqueIDX is an alphanumeric string generated by Firebase every time you push() OR add an Todo.

You can use onChildAdded to listen for data.

Upvotes: 1

Related Questions