Home > Enterprise >  NoSuchMethodError: The method 'get' was called on null in Flutter using Dart with Firestor
NoSuchMethodError: The method 'get' was called on null in Flutter using Dart with Firestor

Time:10-28

I'm getting a "NoSuchMethodError: The method 'get' was called on null. Receiver: null Tried calling: get("legpressReps")"

This is my calender log class which accesses documents which based on a specific sport name and time that is entered.

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

This is where I override the initState to access the documents which have a sport name 'weightlifting' and date set to 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];
}
});

When we try to display a data field in the home page, this is how we are trying to access it:

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

CodePudding user response:

Your code in the .then() block runs asyncronously. It might not have completed when you call calendarLogs.get('legPressReps') and if it hasn't, then calendarLogs is still null.

A quick fix would be calendarLog?.get('legPressReps'), but then you need some state management with setState to make sure you notify your builder about the fact that it changed to something that is not null.

Look into What is a Future and how do I use it? to find out how to handle asyncronous behaviour properly in your application.

CodePudding user response:

Try change this line :

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

with this line:

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

If it does not work, try to also change this line :

calendarLogs = docs.docs[0];

with this line:

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

If still does not work, you will need to share your code for this getCalendarLog and a snapshot from your database

see more in this link on how QuerySnapshot work.

  • Related