答案更多在于你的架构而不是任何东西。
1. 在管理项目复杂性方面,静态路由是两者中的佼佼者。路线定义清晰,供多个开发人员理解,导航代码更容易,Navigator.of(context).pushNamed('your-route');
vs
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
2. 动态页面通常用于教程等以减少样板代码。它只是导航的快捷方式。这样做的缺点是变得难以管理路线,因此应该仅限于简短的教程。
3. Generated Routes还有第三种选择,在我看来是两者中最好的,那就是 Generated Routes。这是最干净和最容易维护的结构。这里有一个很棒的教程。这是纲要:
- 声明路线:
class RoutePaths {
static const Start = '/';
static const SecondScreen = 'second'
}
- 声明你的路由器:
class Router {
static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
case RoutePaths.Start:
return MaterialPageRoute(builder: (_) => YourFirstScreenWidget());
case RoutePaths.SecondScreen:
// you can do things like pass arguments to screens
final event = settings.arguments as Event;
return MaterialPageRoute(
builder: (_) => YourSecondScreenWidget(event: event));
default:
return MaterialPageRoute(
builder: (_) => Scaffold(
body: Center(
child: Text('No route defined for ${settings.name}'),
),
));
}
}
}
- 在 main.dart 中声明
initialRoute: RoutePaths.Start,
onGenerateRoute: Router.generateRoute,
- 导航
// arguments: event is an optional parameter to send to secondScreen
Navigator.of(context).pushNamed(RoutePaths.SecondScreen, arguments: event);