First step in using Firebase within Flutter app is to perform initialization.
I’ve tried doing this within main() and it works
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
I’ve utilized Riverpod for state management – with Provider for firebase instance and access to the class with connection methods (Signin, Signout…) and StreamProvider for user state.
Again this works fine – recognizing when the user has signed in or signed out – rebuilding widgets and redirecting to proper screen…
Now I would like to also move the code pasted above from main() into a provider definition and have shown proper screen depending on the status of firebase initialization.
I’ve seen official Firebase example suggesting to use FutureBuilder for this – however, since I’ve used Riverpod – my idea was to use FutureProvider
for initializing firebase.
However, whatever I try the app keeps crashing with some null exceptions.
If anybody can share their example of firebase.initializeApp()
via FutureProvider it would be great.
2
Answers
I've found a solution for this so pasting it bellow. Big thanks to 2002Bishwajeet who posted a Firebase & Riverpod authentication example covering this topic as well at GitHub
The idea is to create FutureProvider like this:
In the main() keep just
WidgetsFlutterBinding.ensureInitialized()
Like this:Then watch the provider and use .when() to show the correct screen - basically to move to AuthenticationWrapper widget only once the Firebase.initializeApp() has completed the initialization process.
Like this:
And finally the AuthenticationWrapper is handling display of SignIn or Home screen - depending on the status of the user (already signed in at Firebase Auth or not).
Like this:
I do it like this: (Can be done via singleton if needed)
The main file looks like this: