'Getting this flutter error when calling the nested list of data from firestore database. Getting null method call []("orientation")

I'm getting this null error when calling the firebase firestore database. It's working fine with my other data. Only getting error with this nested List of 'orientation'. Please help with this.

E/flutter (21191): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
    E/flutter (21191): Receiver: null
    E/flutter (21191): Tried calling: []("orientation")
    E/flutter (21191): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
    E/flutter (21191): #1      new User.fromDocument (package:meetapp/models/user_model.dart:59:41)
    E/flutter (21191): #2      TabbarState.getUserList.<anonymous closure>.<anonymous closure> (package:meetapp/Screens/Tab.dart:407:40)
    E/flutter (21191): #3      TabbarState.getUserList.<anonymous closure>.<anonymous closure> (package:meetapp/Screens/Tab.dart:399:26)
    E/flutter (21191): #4      _rootRunUnary (dart:async/zone.dart:1434:47)
    E/flutter (21191): #5      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
    E/flutter (21191): <asynchronous suspension>
    E/flutter (21191): 

error log and model class

and this is the firebase data collection



Solution 1:[1]

As you see, your doc.data() is not null, but you should also null-check ['sexualOrientation'] property. In your case, it's null, and you should write catch method for this case, because now you trying to call another property without asserting it. Let me explain.

Here is your data:

doc.data()! | is not null

?

['sexualOrientation'] | is null so next value cant be accessed

?

['orientation'] | cant be accessed because previous is null

What can you do:

Add assertation for second, potentionally nullable field. You can use ! or ? to check if it's null, like doc.data()!['sexualOrientation']!['orientation'] ?? []

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Electron