I'm still new and in progress of understanding flutter, so please somebody tell me which is wrong. My code for auto login is as following :
class _login_pageState extends State<login_page> {
void initState() {
super.initState();
final auth = FirebaseAuth.instance;
print(auth.currentUser);
if (auth.currentUser !=null)
{
Navigator.of(context).push(MaterialPageRoute(builder: (context) =>main_bone()));
}
// Enable virtual display.
}
@override
Widget build(BuildContext context) {
...
My intention is to automatically login when auth.currentUser exists, and navigate to main_bone()
class. By print code I confirmed the auth correctly gets login-ed user info.
The error message I got is this.
Exception caught by widgets library =======================================================
The following assertion was thrown building Builder:
setState() or markNeedsBuild() called during build.
...
'package:flutter/src/widgets/navigator.dart': Failed assertion: line 5127 pos 12: '!_debugLocked': is not true.
I saw these error message several times but still not completely understanding why this appears. Please tell me what I did wrong and why these error occurs.
CodePudding user response:
Try using the StreamBuilder
and userChanges
provided by Firebase to listen to authentication events. Try in your main function
home: StreamBuilder(
stream: FirebaseAuth.instance.userChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
if (snapshot.hasData) {
return main_bone();
} else if (snapshot.hasError) {
return Center(
child: Text('${snapshot.error}'),
);
}
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return const LoginPage();
},
),