示例工程 ch16-bookmarks

ch16-bookmarks/lib/src/presentation/router.dart

dart · 1.7 KB

// 路由:go_router。声明式配置 + 路径参数,比逐层 Navigator.push 更容易看全貌。
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
 
import 'pages/detail_page.dart';
import 'pages/editor_page.dart';
import 'pages/home_page.dart';
 
final routerProvider = Provider<GoRouter>((Ref ref) {
  final GoRouter router = GoRouter(
    initialLocation: '/',
    routes: <RouteBase>[
      GoRoute(
        path: '/',
        builder: (BuildContext context, GoRouterState state) => const HomePage(),
        routes: <RouteBase>[
          GoRoute(
            path: 'new',
            builder: (BuildContext context, GoRouterState state) => const EditorPage(),
          ),
          GoRoute(
            path: 'bookmark/:id',
            builder: (BuildContext context, GoRouterState state) => DetailPage(
              id: int.tryParse(state.pathParameters['id'] ?? '') ?? -1,
            ),
          ),
        ],
      ),
    ],
    errorBuilder: (BuildContext context, GoRouterState state) => const NotFoundPage(),
  );
  ref.onDispose(router.dispose);
  return router;
});
 
class NotFoundPage extends StatelessWidget {
  const NotFoundPage({super.key});
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('页面不存在')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('没有这个路径', key: Key('not-found')),
            const SizedBox(height: 12),
            FilledButton(onPressed: () => context.go('/'), child: const Text('回首页')),
          ],
        ),
      ),
    );
  }
}