flutterfirebase-authenticationflutter-streambuilder

The following _TypeError was thrown building StreamBuilder<User?>(dirty, state: _StreamBuilderBaseState<User?, AsyncSnapshot<User?>>):


In my streambuilder - first time i am getting snapshot null value. and shows me error. Null check operator used in a null value.

Here is my main widget that shows me error. Main app state:

 home: _getLandingPage(),

widget that shows me error

 Widget _getLandingPage() {
return StreamBuilder<User?>(
  stream: FirebaseAuth.instance.authStateChanges(),
  builder: (BuildContext context, snapshot) {
    debugPrint('From landing method: ');
    debugPrint('User type: ${userType}');
    debugPrint('snaphsot has data : ${snapshot.hasData}');
    debugPrint(
        'snaphsot provider length : ${snapshot.data!.providerData.length}');
    
    if (snapshot.hasData) {
      if (snapshot.data!.providerData.length == 1 &&
          snapshot.data!.emailVerified) {
        // logged in using email and password
        if (userType == null) {
          return const WelComeScreen();
        }
        return userType == 'TEACHER'
            ? TeacherMainScreen()
            : const StudentMainScreen();
      } 
      else {
        
        return const SignInScreen();
      }
    }
     else {
      debugPrint('snapshot has no data for'); 
      return const SignInScreen();
    }
    
  },
);

}

Debug Console:

From landing method:
User type: Teacher
snapshot has data: false

snapshot has data: false

After some time, snapshot got the data.


Solution

  • This line

    debugPrint('snaphsot provider length : ${snapshot.data!.providerData.length}');
    

    throws the error.

    If snapshot.hasData is false, when you use snapshot.data! will throw "Null check operator used in a null value".

    You can use

    debugPrint('snaphsot provider length : ${snapshot.data?.providerData.length}');