I am trying to implement a simple navigation logger in my flutter app. Created
a new class extending RouteObserver:
class AuthMiddleware extends RouteObserver {
AuthMiddleware();
#override
void didPush(Route route, Route? previousRoute) {
print(
"PUSH FROM ${previousRoute.settings.name} TO ${route.settings.name} ");
super.didPush(route, previousRoute);
}
#override
void didPop(Route route, Route? previousRoute) {
print(
"POP FROM ${previousRoute.settings.name} TO ${route.settings.name}");
super.didPop(route, previousRoute);
}
}
And then assigned it to MaterialApp:
MaterialApp(
navigatorKey: rootNavigatorKey,
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.light,
theme: THEME_DATA,
onGenerateRoute: (RouteSettings settings) {
String? routeName = settings.name;
Widget getPage() {
switch (routeName) {
case "/about":
return AboutPage();
default:
return HomePage();
}
}
return MaterialPageRoute(builder: (context) => getPage());
},
navigatorObservers: [AuthMiddleware()], //***Set created observer here***
),
I was expecting to see that it will print something like
PUSH FROM / TO /about
But I can only see:
PUSH FROM null TO null
What I am doing wrong?
you need to pass settings as a second parameter to MaterialPageRoute
return MaterialPageRoute(builder: (context) => getPage(), settings: settings);
Related
I wonder how we can call generateRoute without arguments
onGenerateRoute: RouteGenerator.generateRoute
my expectation would be:
RouteGenerator.generateRoute(settings)
Thanks,
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: NumberCreator().stream,
builder: (context, snapshot) {
print('StreamBuilder: ${snapshot.connectionState}');
return MaterialApp(
title: 'Demo',
**onGenerateRoute: RouteGenerator.generateRoute,**
onGenerateInitialRoutes: (String initialRouteName) {
return [
RouteGenerator.generateRoute(
RouteSettings(name: '/', arguments: snapshot)),
];
},
);
});
}
}
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case '/':
if (args is AsyncSnapshot<int>) {
It's not really that you are calling onGenerateRoute without arguments, it is because you are passing a parameters which comply to the expected type RouteFactory defined as follow in the flutter documentation:
typedef RouteFactory = Route<dynamic>? Function(RouteSettings settings);
And your generateRoute comply to this type as it is a function which takes a RouteSettings parameter and returning an object of type Route<dynamic>.
Here is the code I've used in my projects:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo',
initialRoute: /*<my_initial_route */,
onGenerateRoute: MyRouter.generateRoute,
);
}
}
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
// your cases ...
default:
return MaterialPageRoute(
builder: (_) => Scaffold(
body: Center(
child: Text('No route defined for ${settings.name}'),
),
),
);
}
}
}
I've looked over several other posts with this same error about the Navigator and either their code looks different, it fails in totally different places, or other reasons and I must be missing something important. Where this fails for me is only from resuming from background or sleep. The app lifecycle detects "resume" and I want to navigate to the login page for the user to select a profile or login. The error below shows any way I try to use a Navigator in that function didChangeAppLifecycleState(AppLifecycleState state). Actually if I use Navigator anywhere in main.dart it gives the error. Outside of main.dart Navigator works great.
Navigator operation requested with a context that does not include a Navigator.
The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
The code that causes the error in main.dart :
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
print("State changed! ${state}");
setState(() {
_notification = state;
});
if(state == AppLifecycleState.resumed){
NavService().navigateTo(context, '/login');
}
}
The main.dart build looks like this:
#override
Widget build(BuildContext context) {
return
MaterialApp(
theme: new ThemeData(
primarySwatch: themeSwatchColor,
brightness: Brightness.light,
primaryColor: themePrimaryColor,
accentColor: themeAccentColor,
),
initialRoute: '/',
navigatorObservers: <NavigatorObserver>[
NavService(), // this will listen all changes
],
onGenerateRoute: (routeSettings) {
switch (routeSettings.name) {
case '/':
return MaterialPageRoute(builder: (_) => LoginPage());
case '/login':
return MaterialPageRoute(builder: (_) => LoginPage());
case '/home':
return MaterialPageRoute(builder: (_) => HomePage());
case '/items':
return MaterialPageRoute(builder: (_) => ItemLookupPage());
case '/settings':
return MaterialPageRoute(builder: (_) => SettingsPage());
case '/oldsettings':
return MaterialPageRoute(builder: (_) => SecondPage());
case '/pickorders':
return MaterialPageRoute(builder: (_) => ReceivedOrdersPage());
case '/orders':
return MaterialPageRoute(builder: (_) => OrdersPage());
case '/receiving':
return MaterialPageRoute(builder: (_) => ReceivingPage());
case '/inventory':
return MaterialPageRoute(builder: (_) => InventoryPage());
default:
return MaterialPageRoute(builder: (_) => LoginPage());
}
},
home: (noAccount == true)
? LoginPage()
: HomePage(),
);
}
NavService.dart:
class NavService extends RouteObserver {
void saveLastRoute(String lastRoute) async {
if(lastRoute != "/login" && lastRoute != "/error"){
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('last_route', lastRoute);
}
}
Future<dynamic> navigateTo(BuildContext context, String routeName, {Map data}) async {
saveLastRoute(routeName);
return Navigator.pushNamed(context, routeName, arguments: data);
}
}
I also tried skipping my NavService and used Navigator directly, but the same error shows.
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => LoginPage(),
),
);
I tried using a GlobalKey as other posts have suggested, but the NavService() using the RouteObserver breaks when I do that.
The NavService and page routing works very well anywhere in the app. Its only while navigating in main.dart I'm having the issue. I just noticed if I place the above Navigator.of().push in initState() I get the same error. Maybe my MaterialApp is setup wrong? Or am I using the NavService incorrectly?
Thanks for any help!
The didChangeAppLifecycleState method does not provide any context unlike the build method. You would have to navigate without using context by setting a global key for your navigation:
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
Pass it to MaterialApp:
MaterialApp(
title: 'MyApp',
onGenerateRoute: generateRoute,
navigatorKey: navigatorKey,
);
Push routes:
navigatorKey.currentState.pushNamed('/someRoute');
Credits to this answer
New to Flutter.
I'm making an app that has a splash screen that initially shows up when the user opens the app. After 3 seconds, the app will show the login or the dashboard screen, depending on the authentication state.
Here's my code.
main.dart
void main() {
runApp(myApp);
}
MaterialApp myApp = MaterialApp(
initialRoute: "/",
routes: {
"/": (context) => SplashScreen(),
"/signin": (context) => SignInScreen(),
"/notes": (context) => NotesScreen(),
},
);
splash_screen.dart
class SplashScreen extends StatefulWidget {
#override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
_goToNextScreen();
}
void _goToNextScreen() {
Future.delayed(
Duration(seconds:3),
() async {
AuthState authState = await Auth.getAuthState();
String route = authState == AuthState.SIGNED_IN ? "/notes" : "/signin";
Navigator.pushReplacementNamed(context, route);
}
);
}
// build() override goes here...
}
I've been debugging the app with a web-server. When the app launches with the url localhost:8000/, everything seems fine. However, if the app started with the url localhost:8000/notes, the splash screen, I think, still gets initiated. What happens is the app will show the notes screen, then after 3 seconds, the app will open another notes screen.
Any ideas?
Because first render always started at root '/', it's preferable to use your own path for splash screen, like
initialRoute: '/splash'.
To hide this path in the address bar, replace routes map with route generator:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
onGenerateRoute: (RouteSettings settings) {
// print current route for clarity.
print('>>> ${settings.name} <<<');
switch (settings.name) {
case '/splash':
return MaterialPageRoute(
builder: (context) => SplashScreen(),
// settings omitted to hide route name
);
case '/signin':
return MaterialPageRoute(
builder: (context) => SignInScreen(),
settings: settings,
);
case '/notes':
return MaterialPageRoute(
builder: (context) => NotesScreen(),
settings: settings,
);
case '/':
// don't generate route on start-up
return null;
default:
return MaterialPageRoute(
builder: (context) => FallbackScreen(),
);
}
},
initialRoute: '/splash',
);
}
}
See since the main logic is we cannot have await in the init state so the page will build irrespective of the any logic you provide. I have a solution to this, there may be some advance or other good solutions too, so this is what I would use.
I would use a concept of future builder. What it will do is wait for my server and then build the whole app.
So process is
In your main.dart
use
Future<void> main() async {
try {
WidgetsFlutterBinding.ensureInitialized();
//await for my server code and according to the variable I get I will take action
//I would have a global parameter lets say int InternetOff
await checkServer();
runApp(MyApp());
} catch (error) {
print(error);
print('Locator setup has failed');
//I can handle the error here
}
}
Now MyApp stateless Widget that will help us choose our path
class MyApp extends Stateless Widget{
Widget build(BuildContext context) {
//Using this FutureBuilder
return FutureBuilder<String>(
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
// AsyncSnapshot<Your object type>
// Now if InternetOff is equal to one I would make it go to home
if(InternetOff==1) return MaterialApp(
theme: ThemeData.light(),
home: CheckInternet(),
debugShowCheckedModeBanner: false,
);
//else go to Home similarly with these if and else you can add more conditions
else {
return MaterialApp(
theme: ThemeData.dark(),
home: UserHome(),
debugShowCheckedModeBanner: false,
);
}
}
}
},
);
}
}
First of all, flutter-web like any other Single Page Application supports hash based routing. As a result if you want to access
localhost:8000/notes
you have to access it as
localhost:8000/#/notes
Cleaner way to handle auth state
Call getAuthState function before runApp() to make sure that the auth state is set before app is initialized. And pass authState to SplashScreen widget as parameter.
void main() {
WidgetsFlutterBinding.ensureInitialized();
AuthState authState = await Auth.getAuthState();
runApp(MaterialApp myApp = MaterialApp(
initialRoute: "/",
routes: {
"/": (context) => SplashScreen(authState: authState),
"/signin": (context) => SignInScreen(),
"/notes": (context) => NotesScreen(),
},
));
}
splash_screen.dart
class SplashScreen extends StatefulWidget {
final AuthState authState;
SplashScreen({Key key, this.authState}) : super(key: key);
#override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
_goToNextScreen();
}
void _goToNextScreen() {
Future.delayed(
Duration(seconds:3),
() async {
String route = widget.authState == AuthState.SIGNED_IN ? "/notes" : "/signin";
Navigator.pushReplacementNamed(context, route);
}
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
}
And if you want even more cleaner way to handle auth state, you have to use state management solution like Provider.
Is there some chance to get current context on the main.dart? I am using the sharing intent for listening applinks, and I need to redirect to specify page. But I don't know how can I use the context.
#override
Widget build(BuildContext context) {
ReceiveSharingIntent.getInitialText().then((String val){
//some logic
Navigator.pushNamed(context, ....);
});
return MaterialApp(
title: 'MyApp',
initialRoute: Routes.home,
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case Routes.home:
return SimplePageRoute(builder: (context) => HomeScreen());
break;
}
}
);
}
I have got this error
Unhandled Exception: Navigator operation requested with a context that
does not include a Navigator.
Ok I am understand, but how can I get the current context in this place?
Ok I fixed it with navigatorKey!!
final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
#override
Widget build(BuildContext context) {
ReceiveSharingIntent.getInitialText().then((String val){
//some logic
navigatorKey.currentState.pushNamed(Routes.myPage);
});
return MaterialApp(
title: 'MyApp',
initialRoute: Routes.home,
navigatorKey: navigatorKey,
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case Routes.home:
return SimplePageRoute(builder: (context) => HomeScreen());
break;
}
}
);
}
How to check previous navigate pages?
Example: HomeScreen > ProductListScreen >ViewCart > Payment (Now I am in the Payment Page)
like this: print(priousPages);
Pass previous page widget as parameter to the Payment widget constructor.
// In page you want to navigate to Payment widget.
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => Payment(priousPages: this.runtimeType);
));
Or, you can use NavigatorObserver to receive events of navigator, and you can record changes of route in observer.
class _NavigatorHistory extends NavigatorObserver {
#override
void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
print("${route.settings.name} pushed");
}
#override
void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
print("${route.settings.name} popped");
}
#override
void didReplace({Route<dynamic> newRoute, Route<dynamic> oldRoute}) {
print("${oldRoute.settings.name} is replaced by ${newRoute.settings.name}");
}
#override
void didRemove(Route<dynamic> route, Route<dynamic> previousRoute) {
print("${route.settings.name} removed");
}
}
You can use route.settings.name to identify the route. So when you create route, you should give a route name.
MaterialPageRoute(
builder: (context) => YourWidget(),
settings: RouteSettings(name: "/payment")
)
Lastly, don't forget to register this observer to App.
MaterialApp(
navigatorObservers:[ _NavigatorHistory()],
title: "App title",
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: homePage,
)