I'm integrating GoRouter in my Flutter app where I'm already using Riverpod. I have an isAuthorizedProvider defined as follows:
final isAuthorizedProvider = Provider<bool>((ref) {
final authStateChanged = ref.watch(_authStateChangedProvider);
final user = authStateChanged.asData?.value;
return user != null;
});
And I'm not sure how to define a GoRouter that depends on the Provider above. I've come up with the following:
final goRouterProvider = Provider<GoRouter>((ref) => GoRouter(
debugLogDiagnostics: true,
redirect: (state) {
final isAuthorized = ref.watch(isAuthorizedProvider);
final isSigningIn = state.subloc == state.namedLocation('sign_in');
if (!isAuthorized) {
return isSigningIn ? null : state.namedLocation('sign_in');
}
// if the user is logged in but still on the login page, send them to
// the home page
if (isSigningIn) return '/';
// no need to redirect at all
return null;
},
routes: [
GoRoute(
path: '/',
...,
),
GoRoute(
name: 'sign_in',
path: '/sign_in',
...,
),
GoRoute(
name: 'main',
path: '/main',
...,
),
...
],
));
class MyApp extends ConsumerWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
final goRouter = ref.watch(goRouterProvider);
return MaterialApp.router(
routeInformationParser: goRouter.routeInformationParser,
routerDelegate: goRouter.routerDelegate,
);
}
Is this the right way to do it?
I don't thing you should be calling this line
ref.watch(isAuthorizedProvider);
inside the redirect block, because that will cause your entire GoRouter instance to rebuild (and you'll lose the entire nav stack).
This is how I've done it:
class AppRouterListenable extends ChangeNotifier {
AppRouterListenable({required this.authRepository}) {
_authStateSubscription =
authRepository.authStateChanges().listen((appUser) {
_isLoggedIn = appUser != null;
notifyListeners();
});
}
final AuthRepository authRepository;
late final StreamSubscription<AppUser?> _authStateSubscription;
var _isLoggedIn = false;
bool get isLoggedIn => _isLoggedIn;
#override
void dispose() {
_authStateSubscription.cancel();
super.dispose();
}
}
final appRouterListenableProvider =
ChangeNotifierProvider<AppRouterListenable>((ref) {
final authRepository = ref.watch(authRepositoryProvider);
return AppRouterListenable(authRepository: authRepository);
});
final goRouterProvider = Provider<GoRouter>((ref) {
final authRepository = ref.watch(authRepositoryProvider);
final appRouterListenable =
AppRouterListenable(authRepository: authRepository);
return GoRouter(
debugLogDiagnostics: false,
initialLocation: '/',
redirect: (state) {
if (appRouterListenable.isLoggedIn) {
// on login complete, redirect to home
if (state.location == '/signIn') {
return '/';
}
} else {
// on logout complete, redirect to home
if (state.location == '/account') {
return '/';
}
// TODO: Only allow admin pages if user is admin (#125)
if (state.location.startsWith('/admin') ||
state.location.startsWith('/orders')) {
return '/';
}
}
// disallow card payment screen if not on web
if (!kIsWeb) {
if (state.location == '/cart/checkout/card') {
return '/cart/checkout';
}
}
return null;
},
routes: [],
);
}
Note that this code is not reactive in the sense that it will refresh the router when the authState changes. So in combination with this, you need to perform an explicit navigation event when you sign-in/sign-out.
Alternatively, you can use the refreshListenable argument.
You can do it this way using redirect, however I've come up with a way that uses navigatorBuilder. This way you maintain the original navigator state (you will be redirected back to whichever page you originally visited on web or with deep linking), and the whole router doesn't have to be constantly be rebuilt.
final routerProvider = Provider((ref) {
return GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => const OrdersScreen(),
),
GoRoute(
path: '/login',
builder: (context, state) => const AuthScreen(),
),
],
navigatorBuilder: (context, state, child) {
return Consumer(
builder: (_, ref, __) =>
ref.watch(authControllerProvider).asData?.value == null
? Navigator(
onGenerateRoute: (settings) => MaterialPageRoute(
builder: (context) => AuthScreen(),
),
)
: child,
);
},
);
});
navigatorBuilder basically allows you to inject some widget between the MaterialApp and the Navigator. We use Riverpod's consumer widget to access the ref and then the whole router doesn't have to be rebuilt, and we can access auth state using the ref.
In my example, ref.watch(authControllerProvider) returns an AsyncValue<AuthUser?>, so if the user is logged in, we return the child (current navigated route), if they are logged out, show them login screen, and if they are loading we can show a loading screen etc.
If you want to redirect users based on roles (e.g. only admin can see admin dashboard), then that logic should go into the redirect function using a listenable as #bizz84 described.
Related
My Flutter project is migrating to go_router and I have trouble understanding how to access riverpod providers in either a GoRoute's build method or redirect method, as I need to access the user's data to control the navigation.
I have a top-level redirect that checks if a user is logged in and sends them to a LoginPage if not. All users can access so-called activities in my app, but only admins can edit them. Whether a user is an admin is stored in a riverpod userDataProvider, which always contains a user if the user is logged in. Now if a user attempts to enter the route /:activityId?edit=true, I want to check whether they are allowed to by accessing the userDataProvider. However, I do not see what the clean way of accessing this provider is.
I found somewhere (can't find the thread anymore), that one way is to use ProviderScope.containerOf(context).read(userDataProvider), but I have never seen this before and it seems a bit exotic to me. Is this the way to go?
My GoRoute looks something like this:
GoRoute(
path: RouteName.event.relPath,
builder: (context, state) {
final String? id = state.params['id'];
final bool edit = state.queryParams['edit'] == 'true';
if (state.extra == null) {
// TODO: Fetch data
}
final data = state.extra! as Pair<ActivityData, CachedNetworkImage?>;
if (edit) {
return CreateActivity(
isEdit: true,
data: data.a,
banner: data.b,
);
}
return ActivityPage(
id: id!,
data: data.a,
banner: data.b,
);
},
redirect: (context, state) {
final bool edit = state.queryParams['edit'] == 'true';
if (edit) {
// IMPORTANT: How to access the ref here?
final bool isAdmin =
ref.read(userDataProvider).currentUser.customClaims.admin;
if (isAdmin) {
return state.location; // Includes the queryParam edit
} else {
return state.subloc; // Does not include queryParam
}
} else {
return state.path;
}
},
),
In my current application, I used something similar approach like this :
Provider registration part (providers.dart) :
final routerProvider = Provider<GoRouter>((ref) {
final router = RouterNotifier(ref);
return GoRouter(
debugLogDiagnostics: true,
refreshListenable: router,
redirect: (context, state) {
router._redirectLogic(state);
return null;
},
routes: ref.read(routesProvider));
});
class RouterNotifier extends ChangeNotifier {
final Ref _ref;
RouterNotifier(this._ref) {
_ref.listen<AuthState>(authNotifierProvider, (_, __) => notifyListeners());
}
String? _redirectLogic(GoRouterState state) {
final loginState = _ref.watch(authNotifierProvider);
final areWeLoggingIn = state.location == '/login';
if (loginState.state != AuthenticationState.authenticated) {
return areWeLoggingIn ? null : '/login';
}
if (areWeLoggingIn) return '/welcome';
return null;
}
}
Main app building as router (app.dart):
class App extends ConsumerWidget {
const App({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context, WidgetRef ref) {
final GoRouter router = ref.watch(routerProvider);
return MaterialApp.router(
routeInformationProvider: router.routeInformationProvider,
routeInformationParser: router.routeInformationParser,
routerDelegate: router.routerDelegate,
debugShowCheckedModeBanner: false,
title: 'Flutter Auth',
}
}
}
And as entrypoint (main.dart):
Future<void> main() async {
F.appFlavor = Flavor.dev;
WidgetsFlutterBinding.ensureInitialized();
await setup();
runApp(ProviderScope(
observers: [
Observers(),
],
child: const App(),
));
}
My app uses flutter with auto_router 0.6.9 package, and I want user to be able to type in a web address http://localhost/#/book/123 and be able to access book 123 and display book123, their name, and email if they are logged in. I had figured out the routing part with auto_router but when the user put the address directly into the browser, the arguments should be passed into the page are null.
I was wondering is there a way to parse the url and pass in the arguments required before displaying the page. Thanks for any help or hints!
My router.dart page:
#MaterialAutoRouter(
routes: <AutoRoute>[
// some other pages...
MaterialRoute(path: "/book/:id", page: MultiProvider),
],
)
class $ModularRouter {}
The router.gr.dart generated for multiprovider arguments class is:
/// MultiProvider arguments holder class
class MultiProviderArguments {
final Key key;
final List<SingleChildWidget> providers;
final Widget child;
final Widget Function(BuildContext, Widget) builder;
MultiProviderArguments(
{this.key, #required this.providers, this.child, this.builder});
}
My book menu page contains a navigation:
(this is an example of how I normally call the BookPage in another page)
child: GestureDetector(
onTap: () => ExtendedNavigator.of(context).push(
Routes.multiProvider(id: book[index].bookID),
arguments: MultiProviderArguments(
providers: [
Provider<UserData>.value(
value: userdata,
),
Provider<List<BookInfo>>.value(
value: book,
),
],
child: BookPage(
bookId: book[index].bookID,
name: userdata.userName,
email: userdata.email,
),
),
),
...
And BookPage takes in 3 arguments bookId, name and email:
class BookPage extends StatefulWidget {
final String bookId;
final String name;
final String email;
BookPage({
this.bookId,
this.name,
this.email,
});
...
}
...
class _BookPageState extends State<BookPage> {
...
Widget build(BuildContext context) {
final currentUser = Provider.of<UserData>(context, listen: false);
final currentBook = Provider.of<List<BookInfo>>(context, listen: false);
...
}
}
I had figured out a Band-Aid solution (which I don't consider to be permanent):
I had abandoned using auto-route which I have no idea how to parse the url and use onGenerateRoute instead:
onGenerateRoute: (settings) {
final settingsUri = Uri.parse(settings.name);
final user = Provider.of<User>(context);
if (user == null) {
return MaterialPageRoute(
builder: (context) {
return LogInPage();
}
);
} else {
// Handle '/'
if (settingsUri.pathSegments.length == 0) {
return MaterialPageRoute(
builder: (context) {
return PageWrapper(false, bookid);
}
);
}
// Handle '/book/:id'
if (settingsUri.pathSegments.length == 2) {
if (settingsUri.pathSegments.first != 'book') {
return MaterialPageRoute(
builder: (context) {
return UnknownPage();
}
);
}
final bookid = settingsUri.pathSegments.elementAt(1);
if (bookid == null) {
return MaterialPageRoute(
builder: (context) {
return UnknownPage();
}
);
}
return MaterialPageRoute(
builder: (context) {
return PageWrapper(false, bookid);
}
);
}
}
//Handle other unknown Routes
return MaterialPageRoute(
builder: (context) {
return UnknownPage();
}
);
}
The PageWrapper authenticates user, build providers, and call BookPage class, I put the code in a place where userData providers had already been initialized:
if (this.needRedirect == true) {
return Scaffold(
...
body: FutureBuilder(
future: Future.wait([userData]),
builder: (context, snapshot) {
return MultiProvider(
providers: [
//initialize using streamproviders
...
],
child: BookPage(
bookId: book[index].bookID,
name: userdata.userName,
email: userdata.email,
),
);
}),
);
}
else {...}
The short answer is I had called the WrapperPage in onGenerateRoutes because the providers are not initialized in main.dart, but they are initialized in WrapperPage. Then I put the redirect code after provider initialization in WrapperPage and called BookPage.
This method had caused other bugs, but it had achieved its purpose.
Upon successful signup, I am trying to send users to the homepage (home) explaining how to use the app. I am doing so through this code block on my signup.dart
onPressed: () async {
try {
User user =
(await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
))
.user;
if (user != null) {
user.updateProfile(displayName: _nameController.text);
Navigator.of(context).pushNamed(AppRoutes.home);
}
}
Which is pointing to the home route
class AppRoutes {
AppRoutes._();
static const String authLogin = '/auth-login';
static const String authSignUp = '/auth-signup';
static const String home = '/home';
static Map<String, WidgetBuilder> define() {
return {
authLogin: (context) => Login(),
authSignUp: (context) => SignUp(),
home: (context) => Home(),
};
}
}
However, when I sign up, the data is rendering in firebase, but the user is not being sent to the home page, and throws this error in my console
Make sure your root app widget has provided a way to generate
this route.
Generators for routes are searched for in the following order:
1. For the "/" route, the "home" property, if non-null, is used.
2. Otherwise, the "routes" table is used, if it has an entry for the route.
3. Otherwise, onGenerateRoute is called. It should return a non-null value for any valid route not handled by "home" and "routes".
4. Finally if all else fails onUnknownRoute is called.
Unfortunately, onUnknownRoute was not set.
Any thoughts on how to rectify?
Have you added onGenerateRoute in your MaterialApp? Like this:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
onGenerateRoute: Router.generateRoute,
initialRoute: yourRoute,
child: YouApp(),
);
}
}
class Router {
static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
case AppRoutes.home:
return MaterialPageRoute(builder: (_) => Home());
case AppRoutes.authLogin:
return MaterialPageRoute(builder: (_) => Login());
case AppRoutes.authSignUp:
return MaterialPageRoute(builder: (_) => SignUp());
default:
return MaterialPageRoute(
builder: (_) => Scaffold(
body: Center(
child: Text('No route defined for ${settings.name}')),
));
}
}
}
}
}
I have 2 pages, page1 andpage2. I want to validate that when the app is opened and there is no token or it is false, it redirects to page1 otherwise it redirects to page2, and when I have more pages I want that if there is a valid token, continues the normal flow of the navigation, I was trying this and I have this problem:
in the gif the token is not defined, the validation apparently does well, but the problem is that it continues to reload the current view, I am looking for something more optimal that avoids loading a route if some condition is not met
how can I solve that?
Map<String, WidgetBuilder> getRoutes() {
return <String, WidgetBuilder>{
'/': (BuildContext context) =>
checkNavigation("/", pag1(), context),
'page1': (BuildContext context) =>
checkNavigation("page1", page1(), context),
'page2': (BuildContext context) =>
checkNavigation("/page2", page2(), context)
};
}
dynamic checkNavigation(
String page, dynamic pageContext, BuildContext context) {
if (storage.token && page == "/") {
//Navigator.pushNamedAndRemoveUntil(context, 'page2', (_) => false);
return page2();
} else if (storage.token == false) {
//Navigator.pushNamedAndRemoveUntil(context, 'page1', (_) => false);
return page1();
} else {
return pageContext;
}
}
in my main:
.
.
.
MaterialApp(
title: 'route validation',
initialRoute: '/',
routes: getRoutes(),
It's better to control this behavior in your own abstractions and change routes only if necessary.
I would recommend to add some splash screen at root route and navigate to appropriate route, once token is initialized.
Future<void> asyncInit() {/*...*/}
void initState() {
/* ... */
asyncInit().then((_) => /* push appropriate first route */);
}
Map<String, WidgetBuilder> getRoutes() {
return <String, WidgetBuilder>{
'/': (BuildContext context) => SplashScreen(),
/* other routes */
};
}
If you need intercept other navigation events you can add your own proxy class, this may be easily implemented using Provider package
class MyNavigator {
final GlobalKey<NavigatorState> navigatorKey;
MyNavigator(this.navigatorKey);
static MyNavigator of(BuildContext context) => context.read<MyNavigator>();
Future<T> pushNamed<T extends Object>(
BuildContext context,
String routeName, {
Object arguments,
}) {
// add any additional logic and conditions here
return navigatorKey.currentState.pushNamed<T>(routeName, arguments: arguments);
}
// add any other methods you need
}
// somewhere at the top of widget tree above Widgets/Material/CupertinoApp widget.
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
// add provider with navigator key above navigator
Provider(
create: (_) => MyNavigator(navigatorKey),
child: MaterialApp(navigatorKey: navigatorKey, /*...*/)
)
// use it
MyNavigator.of(context).pushNamed(...)
There is much work going right now to implement Navigator 2.0 with Router and Pages API, which gives you more control and flexibility on routing.
tracking issue:
https://github.com/flutter/flutter/issues/45938
design docs:
https://flutter.dev/go/navigator-with-router
https://flutter.dev/go/router-and-widgetsapp-integration
Pages API is already available in current stable release, but there is not enough documentation and examples at the moment.
Rather than pushing the user around with Navigator.push when they sign in or out, I've been using a stream to listen for sign in and sign out events.
StreamProvider<FirebaseUser>.value(
value: FirebaseAuth.instance.onAuthStateChanged,
)
It works great for the home route as it handles logging in users immediately if they're still authed.
Consumer<FirebaseUser>(
builder: (_, user, __) {
final isLoggedIn = user != null;
return MaterialApp(
home: isLoggedIn ? HomePage() : AuthPage(),
// ...
);
},
);
However, that's just for the home route. For example, if the user then navigates to a settings page where they click a button to sign out, there's no programmatic logging out and kicking to the auth screen again. I either have to say Navigator.of(context).pushNamedAndRemoveUntil('/auth', (_) => false) or get an error about user being null.
This makes sense. I'm just looking for possibly another way that when they do get logged out I don't have to do any stack management myself.
I got close by adding the builder property to the MaterialApp
builder: (_, widget) {
return isLoggedIn ? widget : AuthPage();
},
This successfully moved me to the auth page after I was unauthenticated but as it turns out, widget is actually the Navigator. And that means when I went back to AuthPage I couldn't call anything that relied on a parent Navigator.
What about this,you wrap all your screens that depend on this stream with this widget which hides from you the logic of listening to the stream and updating accordingly(you should provide the stream as you did in your question):
class AuthDependentWidget extends StatelessWidget {
final Widget childWidget;
const AuthDependentWidget({Key key, #required this.childWidget})
: super(key: key);
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {//you handle other cases...
if (snapshot.currentUser() != null) return childWidget();
} else {
return AuthScreen();
}
},
);
}
}
And then you can use it when pushing from other pages as follows:
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (ctx) => AuthDependentWidget(
childWidget: SettingsScreen(),//or any other screen that should listen to the stream
)));
I found a way to accomplish this (LoVe's great answer is still completely valid) in case anyone else steps on this issue:
You'll need to take advantage of nested navigators. The Root will be the inner navigator and the outer navigator is created by MaterialApp:
return MaterialApp(
home: isLoggedIn ? Root() : AuthPage(),
routes: {
Root.routeName: (_) => Root(),
AuthPage.routeName: (_) => AuthPage(),
},
);
Your Root will hold the navigation for an authed user
class Root extends StatefulWidget {
static const String routeName = '/root';
#override
_RootState createState() => _RootState();
}
class _RootState extends State<Root> {
final _appNavigatorKey = GlobalKey<NavigatorState>();
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
final canPop = _appNavigatorKey.currentState.canPop();
if (canPop) {
await _appNavigatorKey.currentState.maybePop();
}
return !canPop;
},
child: Navigator(
initialRoute: HomePage.routeName,
onGenerateRoute: (RouteSettings routeSettings) {
return MaterialPageRoute(builder: (_) {
switch (routeSettings.name) {
case HomePage.routeName:
return HomePage();
case AboutPage.routeName:
return AboutPage();
case TermsOfUsePage.routeName:
return TermsOfUsePage();
case SettingsPage.routeName:
return SettingsPage();
case EditorPage.routeName:
return EditorPage();
default:
throw 'Unknown route ${routeSettings.name}';
}
});
},
),
);
}
}
Now you can unauthenticate (FirebaseAuth.instance.signout()) inside of the settings page (or any other page) and immediately get kicked out to the auth page without calling a Navigator method.