【Flutter 工程】006-路由跳转:go_router
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerDelegate: GoRouterDelegate(
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) => HomePage(),
routes: <GoRoute>[
GoRoute(
path: 'profile/:id',
builder: (BuildContext context, GoRouterState state) {
final String id = state.params['id']!.toString();
return ProfilePage(id: id);
},
),
],
),
],
errorPageBuilder: (BuildContext context, GoRouterState state) {
return Scaffold(
body: Center(
child: Text('Error: ${state.error}'),
),
);
},
debugLogListenable: _debugLogListenable, // 如果你想看到路由的日志
),
routeInformationParser: GoRouter.routeInformationParser,
routerDelegate: GoRouter.routerDelegate,
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(
child: Text('Go to profile page'),
onPressed: () {
// 使用GoRouter进行路由跳转
GoRouter.of(context).go('/profile/0612');
},
),
),
);
}
}
class ProfilePage extends StatelessWidget {
final String id;
ProfilePage({required this.id});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Profile Page with ID: $id'),
),
);
}
}
这个示例代码展示了如何在Flutter应用中使用go\_router插件来处理路由跳转和参数传递。代码中定义了一个主页面HomePage
和一个个人资料页面ProfilePage
,在HomePage
中有一个按钮可以跳转到ProfilePage
并传递一个ID参数。使用GoRouter
进行路由跳转和参数处理,同时展示了错误页面的自定义构建方法。
评论已关闭