【问题标题】:Expected a value of type 'Map<String, dynamic>', but got one of type '() => Map<String, dynamic>?'应为“Map<String, dynamic>”类型的值,但得到“() => Map<String, dynamic>?”类型之一
【发布时间】:2021-11-15 21:17:18
【问题描述】:

我正在使用 Firebase Cloud Firestore 开发带有 Flutter 的 Web 应用程序。

我想从 Firestore 中获取值,但是发生错误并且无法获取它们。

错误;

需要一个类型为“Map”的值,但得到一个类型为“() => Map?”的值

代码;

  Future<String> getData(String collection, String field) async {
    DocumentSnapshot docSnapshot =
        await FirebaseFirestore.instance.collection(collection).doc().get();
    Map<String, dynamic> record = docSnapshot.data as Map<String, dynamic>;
    return record[field];
  }


FutureBuilder(
              future: getData("users", "userName"),
              builder: (context, snapshot) {
                if (snapshot.connectionState != ConnectionState.done) {
                  return const SizedBox(
                    width: 50,
                    child: LinearProgressIndicator(),
                  );
                }

                if (snapshot.hasError) {
                  return SelectableText(snapshot.error.toString());
                }

                if (!snapshot.hasData) {
                  return const Text('No data found');
                }

                return Text('${snapshot.data}');
              },
            )

这段代码是调用getData()并在发生错误时在屏幕上显示错误语句的FutureBuilder。


经过一番研究,我找到了一种以这种方式消除错误的方法。这样的代码;

Map<String,dynamic> record = new Map<String,dynamic>.from(docSnapshot.data["songs"]);

但是,这在语法上是不正确的,会导致编译错误。 从 2019 年到现在,Firestore 似乎发生了很大变化,是这个原因吗?

docSnapshot.data["songs"]

这对DocumentSnapshot 无效。

谁能解决这个错误?谢谢。

加法1;

我更改了代码,但发生了其他类似的错误。 第一个错误已解决。

    Map<String, dynamic> record = docSnapshot.data() as Map<String, dynamic>;

需要一个类型为“Map”的值,但得到了一个类型 '空'

Firestore 确认数据“userName”正确存在。

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore flutter-web


    【解决方案1】:

    我相信DocumentSnapshot.data是一个方法,所以你应该把它改成:DocumentSnapshot.data()

    【讨论】:

    • 应该是docSnapshot.data.data()
    • 感谢您的回答,我更改了代码,但出现了其他错误。我编辑了问题。
    • @Mudassir 嗨,在哪里写?在我的环境中,docSnapshotdata 没有 data() 方法。
    • 好的,我相信这就是正在发生的事情:FirebaseFirestore.instance.collection(collection).doc() 将获得 collection 集合并在其中创建一个新文档,之后,您获取该文档并尝试获取其数据,它是空的,所以 data() 返回 null。
    • 为什么我得到空数据?有问题的图像显示它在 uid 文档中有字段。如果你有时间,请。
    猜你喜欢
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2021-10-08
    • 2021-11-02
    • 2019-04-03
    • 2021-04-11
    • 1970-01-01
    • 2019-05-02
    相关资源
    最近更新 更多