【问题标题】:Argument type 'List<Todolist>? Function(QuerySnapshot<Object?>)' can't assigned to parameter type 'List<Todolist> Function(QuerySnapshot<Object?>)参数类型 'List<Todolist>? Function(QuerySnapshot<Object?>)' 不能分配给参数类型 'List<Todolist> Function(QuerySnapshot<Object?>)
【发布时间】:2021-12-22 20:00:45
【问题描述】:

Firebase Cloudstore 出现以下错误。我无法将列表函数映射到流列表待办事项 参数类型“列表? Function(QuerySnapshot)' 不能分配给参数类型'List Function(QuerySnapshot)'。

导入“飞镖:数学”;

import 'package:cloud_firestore/cloud_firestore.dart';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:todolist/models/model.dart';

class databaseService {
  CollectionReference todosCollection =
      FirebaseFirestore.instance.collection("Todos");

  Future createNewTools(String title) async {
    await todosCollection.add({
      "title": title,
      "iscomplete": false,
    });
  }

  Future completTask(id) async {
    await todosCollection.doc(id).update({"iscomplete": true});
  }

  Future removeTodo(uid) async {
    await todosCollection.doc(uid).delete();
  }

  List<Todolist>? todoFromFirestore(QuerySnapshot snapshot) {
    if (snapshot != null) {
      return snapshot.docs.map((e) {
        return Todolist(
                iscomplete: e["iscomplete"],
                title: e["title"],
                id: e.id,
        );
      }).toList();
    } else {
      return null;
    }
  }

  Stream<List<Todolist>> listTodo(){
    return todosCollection.snapshots().map(todoFromFirestore); //error
  }

  }

以及 todolist 模型文件:

class Todolist {
  String id;
  String title;
  String iscomplete;

  Todolist({required this.id, required this.title, required this.iscomplete, isComplete});
}

错误:

【问题讨论】:

  • 这里的问题是map方法不能接受null的值。您的todoFromFirestore 签名是List?,这意味着您的方法可能会返回null 值。

标签: firebase flutter google-cloud-firestore


【解决方案1】:
  List<Todolist> todoFromFirestore(QuerySnapshot snapshot) {
    if (snapshot != null) {
      return snapshot.docs.map((e) {
        return Todolist(
                iscomplete: e["iscomplete"],
                title: e["title"],
                id: e.id,
        );
      }).toList();
    } else {
      return [];
    }
  }

一个可为空的列表导致错误。 试试这个...

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2021-10-28
    • 2022-10-02
    • 2020-08-26
    • 2021-12-30
    • 2021-12-24
    • 2021-11-26
    • 1970-01-01
    • 2021-09-26
    相关资源
    最近更新 更多