I'd like a password reset email to navigate me to an app page:
It seems I can have MaterialApp.onGenerateInitialRoutes generate a stack of pages:
- Home
- Password Reset
so that if back is pressed, the user is sent home.
Cool! However. In doing this that Home page widget is not only created by also entirely built. This has a number of problems, including starting a bunch of logic to try to automatically login - not what I want when viewing a password reset page.
- Why does flutter feel the need to immediately build the home page that I am not viewing.
- How can avoid building pages that the user is not at. (e.g. only build if visible).
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
// Define the onGenerateInitialRoutes callback
onGenerateInitialRoutes: (String initialRouteName) {
// This list will hold the routes that will be generated
List<Route<dynamic>> initialRoutes = [];
// Allow navigation back to HomeScreen
initialRoutes.add(
MaterialPageRoute(
settings: RouteSettings(name: '/'),
builder: (context) => HomeScreen(),
),
);
if (initialRouteName == '/pwreset') {
// If the initial route is '/pwreset', push the PWResetScreen
initialRoutes.add(
MaterialPageRoute(
settings: RouteSettings(name: '/pwreset'),
builder: (context) => PWResetScreen(),
),
);
}
// Return the list of initial routes
return initialRoutes;
},
// Define the initial route name
initialRoute: '/pwreset',
routes: {
'/': (context) => HomeScreen(),
'/pwreset': (context) => PWResetScreen(),
},
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("Home Screen Built!");
return Scaffold(
appBar: AppBar(
title: Text('Home Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// Navigate to the pwreset screen
Navigator.pushNamed(context, '/pwreset');
},
child: Text('Go to Details'),
),
),
);
}
}
class PWResetScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("PWResetScreen Built!");
return Scaffold(
appBar: AppBar(
title: Text('Details Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// Navigate back to the home screen
Navigator.pop(context);
},
child: Text('Go Back to Home'),
),
),
);
}
}
class NotFoundScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Not Found'),
),
body: Center(
child: Text('404 - Page Not Found'),
),
);
}
}