我是一个新手,正在学习Flutter。在MaterialApp小部件中,有一个名为onUnknownRoute的属性。onUnknownRoute的主要用途是什么?
谢谢你的帮助!
谢谢你的帮助!
您可以复制下面的完整代码并运行
在 flutter web
中,当用户手动输入未定义的路由时,会产生类似于 404
的效果
完整代码
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();
}
}
onUnknownRoute
属性用于处理应用程序导航无法获取路由的最坏情况。如果未处理,则会生成异常。
导航器小部件管理一组路由对象。 路由对象只是全屏元素,如“屏幕”或“页面”。 导航器管理任何应用程序中屏幕之间的导航。 任何应用程序的Navigator仅在以下项目之一提供路由时构建
return MaterialApp(
title: 'Named Routing',
onGenerateRoute: router.generateRoute,
onUnknownRoute: (settings) => MaterialPageRoute(
builder: (context) => UndefinedView(
name: settings.name,
)),
initialRoute: HomeViewRoute,
);
如果不使用onUnknownRoute属性处理未知路由事件,Flutter可能会抛出异常。解决方案是编写路由 -> 示例
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());
},
);
}
}