Home > Enterprise >  LateInitializationError: Field 'user' has not been initialized. Error in emulator even tho
LateInitializationError: Field 'user' has not been initialized. Error in emulator even tho

Time:07-12

class _HomePageState extends State<HomePage> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  late User user;
  bool isloggedin = false;

  checkAuthentification() async {
    _auth.authStateChanges().listen((user) {
      if (user == null) {
        Navigator.of(context).pushReplacementNamed("start");
      }
    });
  }

This is how I have initialized the user.

  @override
  void initState() {
    super.initState();
    this.checkAuthentification();
    this.getUser();
  }

I have used initstate but I still get the error.

 Container(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    "${user.displayName}",
                      // "${user.email}",
                    style:
                    TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
                  ),
                ),
              ),

I have used containers to display information about every user. It'd be great if someone could help with this error.

CodePudding user response:

By marking a variable as late you make an explicit promise to initialize that variable before you first try to read from it. The error you get is because your code fails to live up to that promise.

Specifically, the problem is that this is an asynchronous operation:

checkAuthentification() async {
  _auth.authStateChanges().listen((user) {
    if (user == null) {
      Navigator.of(context).pushReplacementNamed("start");
    }
  });
}

Calling authStateChanges takes time, so the code in the listen will only be run after a certain, undetermined amount of time. Worse: your listen then defines a user parameter, but it never sets the users field to any value.

The solution is to:

  1. Mark the user field as a nullable variable.
  2. Deal with the fact that the user field may be null in your build code.
  3. Assign user when your authStateChanges stream fires.

In code that'd look something like this:

class _HomePageState extends State<HomePage> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  User? user; //            
  • Related