我对 Flutter 非常陌生,但来自这里的 Angular 背景。假设我想为我的应用程序构建一个 BaseFrame,并且根据路由,我想更改该 BaseFrame 的内部。我不明白这是如何工作的?
在 Angular 中,它会是这样的:
'/page-one': PageOne(),
'/page-two': PageTwo(), children: [
'/part-1': Part1(),
'/part-2': Part2(),
];
在这种情况下,如果您导航到 /page-two/part-1
然后它会加载PageTwo()
,它将加载 Part1()
无论您指定 <app-route></app-route>
上PageTwo()
。我不明白如何在 Flutter 中执行此操作,因为在 Flutter 中,似乎您的 main.dart 中只能有一条平坦路线(在您的 MaterialApp
构建器中)
我能想到的最好的办法就是在PageTwo()
上有一个变量,并且有一种类型的 switch 语句:
switch (subPage) {
case '/part-1':
return Part1();
case '/part-2':
return Part2();
}
但这似乎是一个蹩脚的解决方案。您现在还面临着自己修复动画等问题(因为 MaterialApp
不会自动帮助您)。
这里有一些关于此的内容,但这对于菜鸟来说似乎非常复杂。这真的是正确/唯一的方法吗: Nesting routes with flutter
最佳答案
您可以使用此包 qlevar_router 执行类似的操作
您的案例的完整示例
import 'package:flutter/material.dart';
import 'package:qlevar_router/qlevar_router.dart';
void main() {
runApp(MyApp());
}
class AppRoutes {
final routes = <QRouteBase>[
QRoute(
path: '/page-one',
page: (c) => PageOne(),
),
QRoute(
path: '/page-two',
page: (c) => PageTwo(c),
initRoute: '/part-1',
children: [
QRoute(
path: '/part-1',
page: (c) => Part1(),
),
QRoute(
path: '/part-2',
page: (c) => Part2(),
)
])
];
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerDelegate: QR.router(AppRoutes().routes, initRoute: '/page-one'),
routeInformationParser: QR.routeParser(),
);
}
}
class PageOne extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(children: [
Text('This is page one'),
TextButton(
onPressed: () => QR.to('/page-two/part-1'),
child: Text('To Part 1')),
TextButton(
onPressed: () => QR.to('/page-two/part-2'),
child: Text('To Part 2')),
]),
),
);
}
}
class PageTwo extends StatelessWidget {
final QRouteChild child;
PageTwo(this.child);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(children: [
Text('This is page one'),
TextButton(onPressed: () => QR.back(), child: Text('Back')),
TextButton(
onPressed: () => QR.to('/page-two/part-1'),
child: Text('To Part 1')),
TextButton(
onPressed: () => QR.to('/page-two/part-2'),
child: Text('To Part 2')),
SizedBox(
width: 500,
height: 500,
child: child.childRouter,
)
]),
),
);
}
}
class Part1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(child: Text('This is part 1'));
}
}
class Part2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(child: Text('This is part 2'));
}
}
请注意,当您在子级 part-1
和 part-2
之间导航时,page-tow 根本不会改变
关于Flutter嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56416930/