i don't think anything is wrong with this method, i also use something similar for restarting my app, however there is a problem. when you change the route and get unauthorized it won't open main screen ( because you are no longer in Home widget )
you can try these solutions :
use Builder:
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: MainScreen(),
builder: (context, widget) {
return StreamBuilder(
stream: auth.onAuthStateChanged,
builder: (context, snapshot) {
if (snapshot.hasData) {
return widget;
}
return AuthScreen();
},
),
},
);
}
it fixes the issue but you may have data in your widget that may be invalid due to Unauthentication so my suggestion is to restart app like this :
double appKey = 0;
@overrdie
initState() {
super.initState();
auth.onAuthStateChanged.listen(() {
setState(() { appKey++; });
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
key: Key('$appKey'),
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: new StreamBuilder(
stream: auth.onAuthStateChanged,
builder: (context, snapshot) {
if (snapshot.hasData) {
return MainScreen();
}
return AuthScreen();
},
),
);
}
but if you are sure you handle invalid data it's better to listen to onAuthStateChanged
( like in code above ) and push AuthScreen
via navigator and block user from exiting screen using WillPopScope
widget in AuthScreen
. It feels better because of transition animation.