【问题标题】:flutter/firebase - The method XX was called on nullflutter/firebase - 方法 XX 在 null 上被调用
【发布时间】:2020-12-17 11:21:00
【问题描述】:

我是 Flutter 的新手,我正在尝试集成一个 Firebase 后端来存储我的数据。我正在尝试使用 firebase 建立流,但是当我尝试使用流创建列表视图时,我收到以下消息:

The method 'collection' was called on null.
Receiver: null
Tried calling: collection("betslips")

这是我的代码:

  class Database {
  final FirebaseFirestore firestore;

  Database(this.firestore);

  Stream<List<BetSlipModel>> streamBetSlip({String uid}) {
    try {
      print(firestore.collection("betslips"));
      return firestore
          .collection("betslips")
          .snapshots()
          .map((query) {
            List<BetSlipModel> retVal;
            for(final DocumentSnapshot doc in query.docs) {
              retVal.add(BetSlipModel.fromDocumentSnapshot(documentSnapshot: doc));
            }
            return retVal;
      });
    } catch(e) {
      rethrow;
    }
  }
}

然后我尝试访问此处的值:

body:  Expanded(
  child: StreamBuilder(
    stream: Database(widget.firestore)
        .streamBetSlip(uid: widget.auth.currentUser.uid),
    builder: (BuildContext context,
        AsyncSnapshot<List<BetSlipModel>> snapshot) {
      if (snapshot.connectionState == ConnectionState.active) {
        if (snapshot.data.isEmpty) {
          return const Center(
            child: Text("Empty"),
          );
        }
        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (_, index) {
            return BetSlipCard(
              firestore: widget.firestore,
              uid: widget.auth.currentUser.uid,
              betslip: snapshot.data[index],
            );
          },
        );
      } else {
        return const Center(
          child: Text("loading..."),
        );
      }
    },
  ),
),

有什么想法吗?谢谢

【问题讨论】:

  • 如果不给firestore赋值,就会发生null.collection("betslips"),null没有任何方法
  • @TJMitch95 你试过我的答案了吗?

标签: firebase flutter google-cloud-firestore


【解决方案1】:

在 null 上调用了方法“collection”。 接收方:空 尝试调用:collection("betslips")

表示firestore 变量没有引用任何内容,请查看以下解决方法:

你在这里创建了一个类的实例:

stream: Database(widget.firestore)

widgetState类的实例变量,因此在State类内部初始化firestore:

final FirebaseFirestore firestore = FirebaseFirestore.instance;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-07
    • 2021-02-16
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2020-06-12
    • 2020-06-07
    相关资源
    最近更新 更多