Home > other >  The argument type 'List<Todo>? Function(QuerySnapshot<Object?>)' can't be
The argument type 'List<Todo>? Function(QuerySnapshot<Object?>)' can't be

Time:12-21

Okay so basically I have this project, I want to create a database for my app so I add firebase on my project like I always do and I create my database_service file but I have this error in it if somoene can help I will be really greateful as always .

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:have_to/model/todo.dart';

class DatabaseService{
CollectionReference todosCollection = FirebaseFirestore.instance.collection("Todos");
Future createNewTodo(String title) async{
return await todosCollection.add({
  "title":title,
  "isComplet":false,
});
}
Future completTask(uid)async{
await todosCollection.doc(uid).update({"isComplet":true});
}

List<Todo>? todoFromFirestore(QuerySnapshot snapshot){
if(snapshot != null){
  snapshot.docs.map((e) {
    return Todo(uid: e.id,
      title: (e()["title"]),
      isComplet: e()["isComplet"],);
  }).toList();
  }else{
  return null;
     }
    }
  Stream<List<Todo>> listTodos() {
  return todosCollection.snapshots().map(todoFromFirestore);
   }
  }
              

CodePudding user response:

Your stream looks like this:

Stream<List<Todo>> listTodos() {
  return todosCollection.snapshots().map(todoFromFireStore);
}

that means that it will go to firestore and for each document, it will run todoFromFireStore and it will return a list of todos.

todoFromFirestore looks like this:

List<Todo>? todoFromFirestore(QuerySnapshot snapshot){
  if(snapshot != null){
    // some code
  }
}

Three important things here:

  1. it returns List<Todo>?, which means it could return null, but your stream is of type Stream<List<Todo>>, which means it will never have a null value ever. Here is where your error arrives.

  2. Looking at the code on the method, you return null if snapshot is null. snapshot is a QuerySnapshot, it will never be null because it's type is not QuerySnapshot?.

  3. Minor thing but you missed adding a return statement on your method, so it will actually always return null no matter what.

so if you remove the if statement, you change the return type, and you actually return the result itself; the error will fix itself:

List<Todo> todoFromFirestore(QuerySnapshot snapshot){
  return snapshot.docs.map((e) {
    return Todo(uid: e.id,
      title: (e()["title"]),
      isComplet: e()["isComplet"],);
    }).toList();
  }
  • Related