Reputation: 9389
I'm new to flutter, In MaterailApp Widget have an attribute called onUnknownRoute. What is the main use of onUnknownRoute?
Thanks for your help!
Upvotes: 10
Views: 8649
Reputation: 11
The solution is coding in routes -> Example
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
// home: HomePage(),
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => HomePage(),
'alert': (BuildContext context) => AlertPage(),
'avatar': (BuildContext context) => AvatarPage(),
},
***onUnknownRoute: (settings) {},***
onGenerateRoute: (settings) {
return MaterialPageRoute(
builder: (BuildContext context) => AlertPage());
},
);
}
}
Upvotes: 1
Reputation: 177
onUnknownRoute property is used to handle the worst case when the app navigation fails to get a route. If not handled, exception will be generated.
The navigator widget manages a stack of Route objects. Route objects are nothing but full-screen elements like "screens" or "pages". The navigator manages navigation between the screens in any app. The Navigator for any app is only built if routes are provided by one of below items
return MaterialApp( title: 'Named Routing', onGenerateRoute: router.generateRoute, onUnknownRoute: (settings) => MaterialPageRoute( builder: (context) => UndefinedView( name: settings.name, )), initialRoute: HomeViewRoute, );
If unknown route event is not handled using the onUnknownRoute property, flutter may throw an exception
Upvotes: 6
Reputation: 54397
You can copy paste run full code below
In flutter web
, when user manually key a undefine route, it can produce like 404
effect
full code
import 'package:flutter/material.dart';
void main() {
runApp( MaterialApp(
initialRoute: "/screen1",
routes: <String, WidgetBuilder>{
'/screen1': (BuildContext context) => Screen1(),
'/screen2': (BuildContext context) => Screen2(),
'/screen3': (BuildContext context) => Screen3(),
'/screen4': (BuildContext context) => Screen4()
},
onUnknownRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) =>
Scaffold(body: Center(child: Text('Not Found'))),
);
},
)
);
}
class Screen1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
class Screen2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
class Screen3 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
class Screen4 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
Upvotes: 12