Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Null check operator used on a null value

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();
        }
      },
    );
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading