Home > Net >  Null check operator used on a null value
Null check operator used on a null value

Time:12-30

I'm getting this error when i was tried to use different pages based on the user role. I don't know how should I use the ? or ! in the StreamBuilder or the class itself. i don't know it said that the userDoc is null.

Null check operator used on a null value

class Start extends StatelessWidget {
  const Start({super.key});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.hasData && snapshot.data != null) {
          UserHelper.saveUser(snapshot.data!);
          return StreamBuilder<DocumentSnapshot>(
            stream: FirebaseFirestore.instance
                .collection('users')
                .doc('Tma4901vh0aXGHjbsvtp8k0fTJS2')
                .snapshots(),
            builder: (BuildContext context,
                AsyncSnapshot<DocumentSnapshot> snapshot) {
              final userDoc = snapshot.data;
              final user = userDoc!.data(); // Here is the error
              if ((user as Map<String, dynamic>)['role'] == 'admin') {
                return const Home();
              } else {
                return const UserHome();
              }
            },
          );
        } else if (snapshot.hasError) {
          return const Center(child: Text('Algo ha salido mal!'));
        } else {
          return const LoginScreen();
        }
      },
    );
  }
}

CodePudding user response:

Wrap this code with if(snapshot.hasData)

final userDoc = snapshot.data;
final user = userDoc!.data();
  if ((user as Map<String, dynamic>)['role'] == 'admin') {
      return const Home();
  } else {
      return const UserHome();
  }

Then it would be like that:

if(snapshot.hasData){
    final userDoc = snapshot.data;
    final user = userDoc!.data();
    if ((user as Map<String, dynamic>)['role'] == 'admin') {
       return const Home();
    } else {
       return const UserHome();
    }
}else{
    return TheWidgetYouWant();
}

CodePudding user response:

Try this:

  if(snapshot.hasData){
    final userDoc = snapshot.data;
    final user = userDoc!.data();
    if ((user as Map<String, dynamic>)['role'] == 'admin') {
       return const Home();
    } else {
       return const UserHome();
    }
  } else {
    return Container();
  }
  • Related