Making Private Route in Flutter
1,024
If you are using routes
parameter in your MaterialApp
, you can replace it with following implementation
import 'dart:collection';
import 'package:flutter/widgets.dart';
class ConditionalRouter extends MapMixin<String, WidgetBuilder> {
final Map<String, WidgetBuilder> public;
final Map<String, WidgetBuilder> private;
ConditionalRouter({this.public, this.private});
@override
WidgetBuilder operator [](Object key) {
if (public.containsKey(key))
return public[key];
if (private.containsKey(key)) {
if (MyAuth.isUserLoggedIn)
return private[key];
// Adding next page parameter to your Login page
// will allow you to go back to page, that user were going to
return (context) => LoginPage(nextPage: key);
}
return null;
}
@override
void operator []=(key, value) {}
@override
void clear() {}
@override
Iterable<String> get keys {
final set = Set<String>();
set.addAll(public.keys);
set.addAll(private.keys);
return set;
}
@override
WidgetBuilder remove(Object key) {
return public[key] ?? private[key];
}
}
And use it like that:
MaterialApp(
// ...
routes: ConditionalRouter(
public: {
'/start_page': (context) => StartPage()
},
private: {
'/user_profile': (context) => UserProfilePage()
}
)
)
Author by
Ravi Garg
I am a learner and tech geek. I love to accept challenges and learn new things on my journey of solving them. I know plenty of languages, except Java, like C, C++, Python, JS, etc. It doesn't mean I don't know Java. I know OOPs:D
Updated on December 01, 2022Comments
-
Ravi Garg over 1 year
How can I make a wrapper over my private routes, which navigate to screen only when user is authorized, otherwise redirect to login and get back to the original screen after login. How can make this in a generalized way, so that I just reuse it on my other Private future screens?
-
Ravi Garg almost 4 yearsI am not using streams from my node server for authentication. Still would take a look on it.
-
Sachin Bhankhar almost 4 yearsCreate a Stream in dart and when user authenticated put data in it.
-
Dmytro Rostopira almost 4 yearsI guess, he already has some static var, that says if user is logged in. Also, stream won't solve problem of routing. Also bloc could be an overkill for beginner
-
Sergei Eensalu over 3 yearsThank you for interesting solution. What are the possibilities to use the async "Auth().isAuth()" function method instead of "MyAuth.isUserLoggedIn" inside your solution? I tried a lot of variants, but no one work :( . Can you help ?
-
Dmytro Rostopira over 3 years@SergeiEensalu you just have to create wrapper for
Navigator
, that's pretty straightforward to do -
Sergei Eensalu over 3 yearsthank you for fast answer. I am new in Flutter, can you please give an example? :)
-
Dmytro Rostopira over 3 years@SergeiEensalu that's not a one-liner comment thing ;) Post this as a separate question, maybe I will find time to answer it later
-
Sergei Eensalu over 3 years