【问题标题】:The method was called on null With DocumentSnapshot and Firestore使用 DocumentSnapshot 和 Firestore 在 null 上调用该方法
【发布时间】:2021-04-27 00:37:53
【问题描述】:

基本上我需要将一个集合的字段保存在一个列表中。

这是负责连接到数据库的小部件:

Future<DocumentSnapshot> MissionRetriever1() async{
    return await FirebaseFirestore.instance
        .collection("quest")
        .doc("1")
        .get();
    }

这是另一个文件中包含的小部件,负责将各种数据保存在列表中:

 Future<void> getMission1() async{
    DocumentSnapshot snap = await widget.mservice.MissionRetriever1();
      Map<String,dynamic> data = snap.data();
      setState(() {
      MissionData1.add(data['Q_Category']);
      MissionData1.add(data['Q_Name']);
      MissionData1.add(data['Q_Description']);
      MissionData1.add(data['Q_Score']);
      MissionData1.add(data['Q_Target']);
    });
  }

但是当我尝试在这样的 Text 小部件中的 List 内显示一个值时:

Text(MissionData1.isEmpty ?  "Loading..." : MissionData1[1],
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontFamily: 'Roboto',
                                      color: const Color(0xFF3A404C),
                                      fontSize: 14.0.sp),),

它总是停留在:“Loading...”并返回这个错误:

E/flutter ( 3639): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method 'MissionRetriever1' was called on null.
E/flutter ( 3639): Receiver: null
E/flutter ( 3639): Tried calling: MissionRetriever1()

这是 Firestore 集合:

这是初始化方法:

@override
  void initState() {
    super.initState();
    asyncMethod();
  }

  void asyncMethod() async {
    **await getMission1();**
    await widget.auth.retrieveScore();
    **await widget.mservice.MissionRetriever1();**
    await widget.mservice.NumberGenerator();
  }

这是列表初始化:**List&lt;String&gt; MissionData1 = [];**

P.S : 查看 Firestore 日志没有拒绝连接

【问题讨论】:

  • 您分享的错误只是意味着您的mservicenull。这应该是您需要检查的第一件事。

标签: flutter google-cloud-firestore flutter-layout flutter-dependencies flutter-test


【解决方案1】:

更改您的方法“MissionRetriever1()”,看看您是否能够恢复数据

return FirebaseFirestore firestore = FirebaseFirestore.instance
.collection('quest')
.doc("1")
.get()
.then((DocumentSnapshot documentSnapshot) {
  if (documentSnapshot.exists) {
    print('Document data: ${documentSnapshot.data()}');
  } else {
    print('Document does not exist on the database');
  }
});

【讨论】:

  • 我试过了,但调试中没有打印任何内容
  • @MatteoGrondona 如果你只放了一个打印语句,这是打印的吗?我认为这不是 Firestore 问题,也许是代码流问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 2020-06-07
  • 2021-07-03
  • 1970-01-01
  • 2019-03-10
  • 2019-12-26
  • 1970-01-01
相关资源
最近更新 更多