Since "named routes are no longer recommended for most applications" how can you change the URL in web browser when you push a new route onto Navigator stack?
E.g. URL is http://localhost:37291/#/ and after performing
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondRoute()),
);
I would want it to change to http://localhost:37291/#/secondRoute.
In the same official docs you have provided there is link for the go_router, which is preferred by flutter team
You can use the path property of GoRoute to achieve the desired url
Initial setup:
// GoRouter configuration
final _router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomeScreen(),
),
GoRoute(
path: '/secondRoute', // 👈 here you can add the path
builder: (context, state) => SecondScreen(), // This is the desired screen you would want to go to
),
],
);
Now your url when routing to SecondScreen would be http://localhost:37291/#/secondRoute
If you want to have the very same functionality you had with Navigator stack you need to implement stuff around Router class. Find out more in this article. You could possibly refer this article for the same.
Further reference:
Flutter: go_router how to pass multiple parameters to other screen?
Related
I have a small Flutter app with 2 screens (/login & /home) and I use go_router to navigate and animated_login. The assets are placed on the home screen and they load fine if I directly access the screen, so pubspec.yaml is correctly defined.
The images fail to load only when I redirect to /home after /login. One interesting observation is that when this happens, the Flutter dev server seems to be hanging (stops responding, but doesn't crash, can't restart it with R, the browser tab complains that it lost connection to the server etc.). This problem occurs also with a combination of auto_route and flutter_login.
Thanks for any hints.
Router setup (tried also w/ the redirect parameter at router level rather than individual routes):
GoRouter routerGenerator(UserData userData) {
return GoRouter(
initialLocation: Routes.home,
refreshListenable: userData,
debugLogDiagnostics: true,
routes: [
GoRoute(
path: Routes.home,
builder: (_, __) => BasicScreen(),
redirect: (state) => userData.loggedIn ? null : Routes.login
),
GoRoute(
path: Routes.login,
builder: (_, __) => AnimLoginScreen(),
redirect: (state) => !userData.loggedIn ? null : Routes.home
),
GoRoute(path: '/', builder: (_, __) => BasicScreen())
]);
}
abstract class Routes {
static const home = '/home';
static const login = '/login';
}
Main app:
void main() {
runApp(
MultiProvider(providers: [
//other providers here
ChangeNotifierProvider(create: (_) => UserData()),
], child: MyApp()),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
final router =
routerGenerator(Provider.of<UserData>(context, listen: false));
return MaterialApp.router(
title: 'Playground',
routeInformationParser: router.routeInformationParser,
routeInformationProvider: router.routeInformationProvider,
routerDelegate: router.routerDelegate,
);
}
}
Basic screen:
class BasicScreen extends StatelessWidget {
BasicScreen({super.key});
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Image(image: AssetImage("assets/images/image1.png")),
Image(image: AssetImage("assets/images/image2.png")),
Image(image: AssetImage("assets/images/image3.png")),
],
),
);
}
}
Solution
Provide a simple proxy over both Flutter DevTool & backend services with SSL capabilities.
Explanation
The issue has nothing to do with routing, but rather the dev setup. Our backend services require SSL connections, but Flutter dev tool doesn't support that. Flow:
Flutter DevTool starts the project (plain HTTP) and opens Chrome window.
Assets load ok.
User logs in, backend service requires HTTPS for secure cookies.
Browser upgrades all localhost connections to HTTPS.
Flutter DevTools fails to provide SSL connection.
Assets fail to load.
The hanging DevTool is caused by the same issue: seems to me that the DevTool is pending the WebSocket connection to be opened by the JS code running in the browser, but as the browser initiates an HTTPS connection to the DevTool, it even fails to load the JS code. Therefore, the DevTool never completes the init process (as it has no incoming connection).
I'm using go_router on web and I would like to implement a different redirect logic between the call of the go_router's API (push, go, replace) and when the user enters an URL in the browser address bar.
I didn't find any solution and I was going to implement it this way:
If I understood correctly, when the user enters an URL in the browser address bar, it restarts the application from scratch, while calling the API doesn't. And I came to this:
bool _isFirstRedirect = true;
GoRouter(
routes: myRoutes,
redirect: (state) {
if (_isFirstRedirect) {
// Logic when the user enters an URL in the browser's address bar.
_isFirstRedirect = false;
} else {
// Logic when it comes from a call of the go_router's API.
}
},
);
But I'm not sure that is a good design. Is there a better way to do that?
Use initialLocation in GoRouter constructor. Something like this:
GoRouter(
initialLocation: '/page3',
routes: [
GoRoute(
path: '/',
builder: (context, state) => const Page1Screen(),
),
GoRoute(
path: '/page2',
builder: (context, state) => const Page2Screen(),
),
GoRoute(
path: '/page3',
builder: (context, state) => const Page3Screen(),
),
],
);
How can I achieve the same effect as the Navigator.pushReplacement does, but in declarative routing with go_router?
Explained
I have 3 pages: /loading, /login, /. And logic is (pseudocode):
/loading {
performSomeComputation();
if checkAuthorization() == authorized {
go /;
} else {
go /login;
}
}
/login {
waitForUserToLogIn();
go /;
}
/ {
// account logic
}
With go_router you can either use .go() or .push().
.push() pushes a new page onto the stack.
.go() works with sub-routes. Every top-level route has got its own stack. Here is a short example:
final GoRouter _router = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
const Page1Screen(),
routes: [
GoRoute(
path: 'page2',
builder: (BuildContext context, GoRouterState state) =>
const Page2Screen(), ),
],
),
GoRoute(
path: '/page3',
builder: (BuildContext context, GoRouterState state) =>
const Page3Screen(),
),
],
);
If you go from the top-level route '/' to the subroute '/page2', '/page2' will be added to the '/' stack. You'll get the back button in the app bar because both '/' and '/page2' are on the stack of top-level route '/'.
If you go from the top-level route '/' to '/page3', you replace the current '/' stack with the '/page3' stack because '/page3' is also a top-level route. You will not see a back button because '/page3' is the first page on the stack of top-level route '/page3'.
What you might be looking for though is redirect. You can pass a redirect function to the GoRouter constructor if you want to redirect on state changes like login and logout. You can combine this with state management libraries like Bloc. You can pass a refreshListenable to the GoRouter constructor that triggers a refresh of the route every time the state stream (yourBloc.stream) changes.
go_router also got a great documentation: https://gorouter.dev/
I am trying to redirect users to my login page if they visit my site without being logged in. I'm trying to use onGenerateRoute to do this. My code in main is this:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseAuth auth = FirebaseAuth.instance;
bool isAuth = auth.currentUser!=null ? true : false;
runApp(MaterialApp(
initialRoute: '/initial',
title: 'Repeater Delivery',
theme: ThemeData(...),
onGenerateRoute: (settings) {
if (!isAuth){
print(settings);
return MaterialPageRoute(
builder: (context) => Login(),
settings: RouteSettings(name: '/login'),
);
}
},
routes: {
'/initial': (context) => Home(),
'/home': (context) => Home(),
'/login': (context) => Login(),
'/signup': (context) => Signup(),
'/how_it_works': (context) => HowItWorks(),
'/profile': (context) => UserProfile(),
},
));
}
The page enters the if statement, so I know that that's working correctly, but I'm not sure how to then redirect to my login page. Also, when I go to a page on my site like www.site.com/#/profile and print out the settings from onGenerateRoute, it just prints a setting name of '/' instead of '/profile'. What am I doing wrong?
According to documentation MaterialApp.onGenerateRoute :
The route generator callback used when the app is navigated to a named
route.
If this returns null when building the routes to handle the specified
initialRoute, then all the routes are discarded and
Navigator.defaultRouteName is used instead (/). See initialRoute.
During normal app operation, the onGenerateRoute callback will only be
applied to route names pushed by the application, and so should never
return null.
This is used if routes does not contain the requested route.
The Navigator is only built if routes are provided (either via home,
routes, onGenerateRoute, or onUnknownRoute); if they are not, builder
must not be null.
Here, your initialRoute is passed to onGenerateRoute, which is not always returning a route (because of the Auth condition). So Navigator is giving another route (the "/") as the initial one. onGenerateRoute must never return null on the App launch task.
Your routes property is only used when you're using pushNamed Navigator's method
I am using the go router plugin for my flutter web application, but I didn't find any way to do push replacement in navigation.
not only push replacement, can we do any other type of navigation link
pushNamedAndRemoveUntil
popUntil
because these navigation options must be needed in kind of any system!
What I tried
context.go(userStorage.redirectURL!);
GoRouter.of(context).go(PagesCollection.adminDashboard);
they only pushed the next page, not replacing
Note: I want this functionality in go router
Try this
Router.neglect(context, () {
context
.goNamed('third', params: {"id": ID});
});
It will neglect your current page. Hop this will helps you
I have had the same problem before. Then this way worked for me
First you need to avoid nested routes:
final GoRouter router = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
const OnboardingScreen(),
),
GoRoute(
path: '/login',
builder: (BuildContext context, GoRouterState state) => LoginScreen(),
),
GoRoute(
path: '/signup',
builder: (BuildContext context, GoRouterState state) =>
const SignupScreen(),
),
],
);
Use the above code instead of nesting like this:
final GoRouter router = GoRouter(
routes: <GoRoute>[
GoRoute(
routes: <GoRoute>[
GoRoute(
path: 'login',
builder: (BuildContext context, GoRouterState state) => LoginScreen(),
),
GoRoute(
path: '/signup',
builder: (BuildContext context, GoRouterState state) =>
const SignupScreen(),
),
],
path: '/',
builder: (BuildContext context, GoRouterState state) =>
const OnboardingScreen(),
),
],
);
This will make you able to replace OnboardingScreen() from the above eg. So next you can use pushreplacement future with:
context.go("/routname");
or
GoRouter.of(context).go("/routname");
If u don't want replacement, then can just use:
context.push("/routname");
or
GoRouter.of(context).push("/routname");
You can do it in a way ->
context.pop();
context.push(routeName);
Adding both these commands works similar to pushReplacement.
In the current version of go_router (5.1.10), you can use GoRouter.of(context).replace('/your-route) to do the same as Navigator.of(context).pushReplacement(yourPage).
There is a PR open to add popUntil but it looks like the flutter team doesn't want to support imperative routing methods and only focus on declarative routing (see, this issue).
It means the popUntil PR might never be merged, and pushNamedAndRemoveUntil never be supported.
It also means that push and replace might be removed in the future.
I am using go_router 6 and it works with:
context.pushReplacement()
What you can do is use Sub-Route Redirects in Go Router.
Let's consider you want users to first go on your Homepage and then from there they tap Login, and go to Login page and then after Logging in, they go to Dashboard Page.
But when they press Browser's Back Button they should go to Homepage and not the LoginPage i.e skipping the LoginPage just like "pushNameReplacement".
Then for this to happen you can configure redirects of each LoginPage and Dashboard page and get this functionality.
You can configure it such that whenever user (including from Browser's History) goes to Dashboard link it first checks if its Logged In then it opens otherwise it displays Login Page automatically.
Edited
i use this functions and they are useful for me
void popUntil(String name){
GoRouter router= AppRoutes.router;
String currentRoute=router.location;
while(router.canPop()&&name!=currentRoute){
currentRoute=router.location;
if(name!=currentRoute){
router.pop();
}
}
}
void pushNamedAndRemoveUntil(String name){
GoRouter router= AppRoutes.router;
while(router.canPop()){
router.pop();
}
router.replaceNamed(name);
}
work same as pushNamedAndRemoveUntil(route_name, (Route<dynamic> route) => false);
any suggestion please drop a comment