skip to Main Content

I am new in Flutter and trying to learn Firebase. In the given below code,I am trying to get data of currentUser that is logged in. But I get _CastError (Null check operator used on a null value). I tried to solve it but couldn’t accomplished it. How can I solve it?

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    final user = FirebaseAuth.instance.currentUser!; 
    var useremail = "Error";
    if (user.email != null) {   //********Problem occurs here**********
      var useremail = user.email;
    }
    print("$user");
    return Scaffold(
        appBar: AppBar(
            title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("HomeScreen"),
          ],
        )),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(useremail),
              ElevatedButton(
                  onPressed: () {
                    FirebaseAuth.instance.signOut(); 
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => MyHomePage(),
                    ));
                  },
                  child: Text("Sign Out")),
            ],
          ),
        ));
  }
}

```

2

Answers


  1. In addition to checking that user.email != null , also verify that the user object is not null.

    Login or Signup to reply.
  2. Replace the above block of code by this:

    final User? user = FirebaseAuth.instance.currentUser; 
    var useremail = "Error";
    if (user?.email != null) {
      useremail = user!.email!;
    }
    

    The problem is that you gave an exclamation after FirebaseAuth.instance.currentUser, that stated that the user can’t be null.

    Also, don’t forget to check if user is null or not before signing him out.

    To learn more about null safety, visit: https://dart.dev/null-safety

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search