0

enter image description here

This is my firestore database structure.

I want to change is_done to true of a todo item to the todo array in the collection.

So far I am able to append an item to the todo

 void addNewTodo() async {
    var db = FirebaseFirestore.instance;

    final querySnapshot = await db
        .collection("users")
        .where("email", isEqualTo: "[email protected]")
        .get();

    for (QueryDocumentSnapshot doc in querySnapshot.docs) {
      doc.reference.update(
        {
          "title": FieldValue.arrayUnion(
              [Todo(isDone: false, description: "Need to Join Gym August Month", title: "Gym").toJson()])
        },
      );
    }
  }


class Todo {
  String? title;
  String? description;
  bool? isDone;

  Todo({this.title, this.description, this.isDone});

  factory Todo.fromJson(Map<String, dynamic> map) {
    return Todo(
        isDone: map['is_done'] ?? false,
        description: map['description'] ?? '',
        title: map['title'] ?? '');
  }

  Map<String, dynamic> toJson() {
    return {
      'title': title ?? '',
      'description': description ?? '',
      'is_done': isDone ?? false
    };
  }
}

class MyUser {
  String? name;
  String? email;
  List<Todo>? todo;

  MyUser({this.name, this.email, this.todo});

  factory MyUser.fromJson(Map<String, dynamic> map) {
    return MyUser(
        name: map['name'] ?? '',
        email: map['email'] ?? '',
        todo: map['todo'] != null
            ? (map['todo'] as List<dynamic>)
                .map((e) => Todo.fromJson(e))
                .toList()
            : []);
  }

  Map<String, dynamic> toJson() {
    return {
      'title': name ?? '',
      'email': email ?? '',
      'todo': todo?.map((e) => e.toJson()).toList()
    };
  }
}

How to update is_done to true of a specific todo item ?

2
  • This has been covered quite a few times by now: there is no way to update an item in an array in Firestore with a single operation. You'll need to: 1) read the document and get the array from it, 2) update the item from within your application code, 3) write the entire array back to the database. Commented Aug 6, 2022 at 13:56
  • okay thanks :) but this question automatically reopened I don't know why Commented Aug 9, 2022 at 6:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.