Skip to main content

03.如何简化Flutter的路由

flutter 出了navigator 2 但是,web的路由和路由栈是不统一的。 就是说如果要把web端的路由和页面栈关联 起来,是需要开发者自己手动处理,这样的就麻烦。那有没有一种,简单的基于url来管理应用的界面呢?我自己封装了一个hi_router 来解决这个问题

安装

$ flutter pub add hi_router

使用示例

import 'package:flutter/material.dart';
import 'package:hi_router/hi_router.dart';
import 'package:hi_router/route/route_abstract.dart';

void main() {
runApp(App());
}

class App extends StatefulWidget {

State<StatefulWidget> createState() => _AppState();
}

class HomePage extends Page {

Route createRoute(BuildContext context) {
return MaterialPageRoute(
settings: this,
builder: (BuildContext context) {
return _HomePageState();
},
);
}
}

class _HomePageState extends StatelessWidget {

Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
child: Column(
children: [
MaterialButton(
onPressed: () {
print("Jump to login page.");
RoutePath.getAppPathInstance().push('/login');
},
child: Text("login page"),
),
],
),
));
}
}

class LoginPage extends Page {

Route createRoute(BuildContext context) {
return MaterialPageRoute(
settings: this,
builder: (BuildContext context) {
return _LoginPageState();
},
);
}
}

class _LoginPageState extends StatelessWidget {

Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
children: [
const Text("Login page."),
TextButton(
onPressed: () {
RoutePath.getAppPathInstance().push('/34343');
},
child: Text("404"))
],
)),
);
}
}

class UnknownPage extends Page {

Route createRoute(BuildContext context) {
return MaterialPageRoute(
settings: this,
builder: (BuildContext context) {
return const UnknownPageRender();
},
);
}
}

class UnknownPageRender extends StatefulWidget {
const UnknownPageRender({Key? key}) : super(key: key);


State<UnknownPageRender> createState() => _UnknownPageRenderState();
}

class _UnknownPageRenderState extends State<UnknownPageRender> {

Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: const Center(
child: Text('Unknown page.'),
));
}
}

class RoutePath {
static HiRouter? _appRoutePathInstance;

static HiRouter getAppPathInstance() {
_appRoutePathInstance ??= HiRouter({
'/': () => HomePage(),
'/login': () => LoginPage(),
});
// 声明未匹配的到路由时,展示的路由
_appRoutePathInstance!.registerUnknownPage =
RoutePageInfo('/404', () => UnknownPage());
// 路由守卫
_appRoutePathInstance!.before = (RoutePageInfo pageInfo) async {
return pageInfo;
};

return _appRoutePathInstance!;
}
}

class _AppState extends State<App> {

Widget build(BuildContext context) {
return RoutePath.getAppPathInstance().build(context, 'App title.');
}
}