【问题标题】:NoSuchMethodError: The method 'get' was called on null in Flutter using Dart with FirestoreNoSuchMethodError:在 Flutter 中使用 Dart 和 Firestore 调用了方法“get”
【发布时间】:2021-12-13 05:49:37
【问题描述】:

我收到“NoSuchMethodError:在 null 上调用了方法 'get'。接收方:null 尝试调用:get("legpressReps")”

这是我的日历日志类,它根据输入的特定运动名称和时间访问文档。

class CalendarLog {
 getCalendarLog(String sportName, Timestamp date) {
 return FirebaseFirestore.instance
.collection('users')
    .where('sport', isEqualTo: sportName)
    .get();
}
}

这是我覆盖 initState 以访问运动名称为“举重”且日期设置为 10-27-2021 的文档的地方

bool calendarLogFlag = false;
var calendarLogs;
@override
void initState(){
super.initState();

DateTime date1 = DateTime.utc(2021, 10, 27);
Timestamp date = Timestamp.fromDate(date1);
CalendarLog().getCalendarLog('weightlifting', date).then((QuerySnapshot docs){
if(docs.docs.isNotEmpty){
  calendarLogFlag  = true;
  calendarLogs = docs.docs[0];
}
});

当我们尝试在主页中显示数据字段时,这是我们尝试访问它的方式:

label: Text(calendarLogs.get('legPressReps') ?? 0),

【问题讨论】:

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


【解决方案1】:

尝试更改此行:

label: Text(calendarLogs.get('legPressReps') ?? 0),

用这一行:

label: Text(calendarLogs["legPressReps"]) ?? 0),

如果不起作用,请尝试更改此行:

calendarLogs = docs.docs[0];

用这一行:

calendarLogs = docs.docs[0].data();

如果仍然无法正常工作,您需要共享此 getCalendarLog 的代码和数据库中的快照

link 中查看更多关于QuerySnapshot 工作原理的信息。

【讨论】:

  • 请不要胡乱猜测。
【解决方案2】:

.then() 块中的代码异步运行。当您调用 calendarLogs.get('legPressReps') 时,它可能尚未完成,如果尚未完成,则 calendarLogs 仍然是 null

快速修复是calendarLog?.get('legPressReps'),但您需要使用setState 进行一些状态管理,以确保通知您的构建者它已更改为非空值。

查看What is a Future and how do I use it?,了解如何在您的应用程序中正确处理异步行为。

【讨论】:

    猜你喜欢
    • 2019-03-10
    • 2020-06-07
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多