I'm working on a web app and have a question about routing. How do you route in combination with Firebase Auth?
On the internet I see a lot of examples with a AuthenticationWrapper. If you are logged in you are going to the home page and if you are not logged in you are going to the Sign in page. That part works. But in the app I want to make more routes.
I learned (Example 1 below) that you can make routes in MaterialApp. I have tried to make this work but it didn't.
How can I route in combination with Firebase Auth and when a user is not logged in it navigates to the Sign in page?
I would love to hear your input on this issue. Thanks in advance!
Main.dart:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<AuthenticationService>(
create: (_) => AuthenticationService(FirebaseAuth.instance),
),
StreamProvider(
create: (context) =>
context.read<AuthenticationService>().authStateChanges,
)
],
child: MaterialApp(
title: 'Name of the app',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: AuthenticationWrapper(),
));
}
}
class AuthenticationWrapper extends StatelessWidget {
@override
Widget build(BuildContext context) {
final firebaseUser = context.watch<User>();
if (firebaseUser != null) {
// Page after loggin in
return HomePage();
}
// Sign in page
return SignInPage();
}
}
Example 1:
MaterialApp(
// Start the app with the "/" named route. In this case, the app starts
// on the FirstScreen widget.
initialRoute: '/',
routes: {
// When navigating to the "/" route, build the FirstScreen widget.
'/': (context) => FirstScreen(),
// When navigating to the "/second" route, build the SecondScreen widget.
'/second': (context) => SecondScreen(),
},
);