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: "ocsdeveloperdevice@gmail.com")
        .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 ?

Balaji
  • 1,773
  • 1
  • 17
  • 30
  • 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. – Frank van Puffelen Aug 06 '22 at 13:56
  • okay thanks :) but this question automatically reopened I don't know why – Balaji Aug 09 '22 at 06:12

0 Answers0