Crash after reset scenes because of focus - flutter

I am trying to make login logout system , every thing works fine
but one scene has auto focus
so when I open the following
login --> focus scene --> logout --> login --> focus scene , after will crash
there is dispose
#override
void dispose() {
_inputFocusNode.dispose();
_textController.dispose();
super.dispose();
}
here when logout:
await Navigator.of(context, rootNavigator: true)
.pushNamedAndRemoveUntil(
'/login', (Route<dynamic> route) => false,);
I run it on web (google chrome)
flutter SDK 3.3.4
Mac os

Difficult to answer with the little code snippet. Check if your routes are configured.
Example:
routes: {
// When navigating to the "/" route, build the FirstScreen widget.
'/': (context) => const FirstScreen(),
// When navigating to the "/second" route, build the SecondScreen widget.
'/second': (context) => const SecondScreen(),
},
Also refer to this stack overflow, if this helps;
Flutter remove all routes

Related

How can you change URL in the web browser without named routes

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?

Flutter image assets not loading after redirect with go_router & login

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).

Flutter GetX - how to implement a loading screen that check the token

So this is the scenario:
I build an app that the first route or the first thing to do is check with a API REST a verification of a token that I already have on localsorage. If the token is valid, proceed to the home page route, if don't we need to redirect them to login screen. All this is async. I already try to get this working adding a route like this:
Widget build(BuildContext context) {
return GetMaterialApp(
initialRoute: '/',
getPages: [
GetPage(
name: '/',
page: () => const AppPage(),
middlewares: [AppPageMiddleware()],
),
GetPage(name: '/login', page: () => const LoginPage()),
GetPage(
name: '/operator', page: () => const OperatorHomePage(), transition: Transition.zoom),
],
);
As you can see, I load a AppPage that the only thing that they do is show the loading spinner. The middleware called AppPageMiddleware uses this:
GetPageBuilder onPageBuildStart(GetPageBuilder? page) async {
// here I perform the call to the API and wait for the response.
// If the API response is true, I need to save the response
// and redirect to OperatorHomePage
print('Bindings of ${page.toString()} are ready');
return page!;
}
But I have an error here because I can't add async.
Maybe this is not the best way to do this, if you can suggest me another way, I will appreciate so much. Sorry, I'm new with GetX.

onGenerateRoute not redirecting with unauthenticated user

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

How can i do push replacement using go router plugin in flutter [go router]

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