Flutter state management with Provider. If you are going to use the FirebaseUser or Logged in user throughout your app, i would suggest that you add the Provider on the highest level of your app. Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { MyApp(); @override Widget build(BuildContext context) { return MultiProvider( providers: [ StreamProvider<FirebaseUser>.value( stream: FirebaseAuth.instance.onAuthStateChanged, // Provider here ), ], child: MaterialApp( title: 'My App', debugShowCheckedModeBanner: false, theme: ThemeData( primaryColor: Colors.green, primarySwatch: Colors.green, accentColor: Colors.yellow, ), home: MainPage(), ), ); } } class MainPage extends StatefulWidget { MainPage({Key key, this.storage}) : super(key: key); final FirebaseStorage storage; @override _MainPageState createState() => _MainPageState(); } class _MainPageState extends State<MainPage> with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { final user = Provider.of<FirebaseUser>(context); // gets the firebase user bool loggedIn = user != null; return loggedIn ? HomePage() : LoginPage(); // Will check if the user is logged in. And will change anywhere in the app if the user logs in } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.