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:
- Mark the
user
field as a nullable variable. - Deal with the fact that the
user
field may be null in yourbuild
code. - Assign
user
when yourauthStateChanges
stream fires.
In code that'd look something like this:
class _HomePageState extends State<HomePage> {
final FirebaseAuth _auth = FirebaseAuth.instance;
User? user; //