router.dart 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright 2013 The Flutter Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. import 'package:flutter/material.dart';
  5. import 'package:go_router/go_router.dart';
  6. /// This sample app shows an app with two screens.
  7. ///
  8. /// The first route '/' is mapped to [HomeScreen], and the second route
  9. /// '/details' is mapped to [DetailsScreen].
  10. ///
  11. /// The buttons use context.go() to navigate to each destination. On mobile
  12. /// devices, each destination is deep-linkable and on the web, can be navigated
  13. /// to using the address bar.
  14. void main() => runApp(const MyApp());
  15. /// The route configuration.
  16. final GoRouter _router = GoRouter(
  17. routes: <RouteBase>[
  18. GoRoute(
  19. path: '/',
  20. builder: (BuildContext context, GoRouterState state) {
  21. return const HomeScreen();
  22. },
  23. routes: <RouteBase>[
  24. GoRoute(
  25. path: 'details',
  26. builder: (BuildContext context, GoRouterState state) {
  27. return const DetailsScreen();
  28. },
  29. ),
  30. ],
  31. ),
  32. ],
  33. );
  34. /// The main app.
  35. class MyApp extends StatelessWidget {
  36. /// Constructs a [MyApp]
  37. const MyApp({Key? key}) : super(key: key);
  38. @override
  39. Widget build(BuildContext context) {
  40. return MaterialApp.router(
  41. routerConfig: _router,
  42. );
  43. }
  44. }
  45. /// The home screen
  46. class HomeScreen extends StatelessWidget {
  47. /// Constructs a [HomeScreen]
  48. const HomeScreen({Key? key}) : super(key: key);
  49. @override
  50. Widget build(BuildContext context) {
  51. return Scaffold(
  52. appBar: AppBar(title: const Text('Home Screen')),
  53. body: Center(
  54. child: Column(
  55. mainAxisAlignment: MainAxisAlignment.center,
  56. children: <Widget>[
  57. ElevatedButton(
  58. onPressed: () => context.go('/details'),
  59. child: const Text('Go to the Details screen'),
  60. ),
  61. ],
  62. ),
  63. ),
  64. );
  65. }
  66. }
  67. /// The details screen
  68. class DetailsScreen extends StatelessWidget {
  69. /// Constructs a [DetailsScreen]
  70. const DetailsScreen({Key? key}) : super(key: key);
  71. @override
  72. Widget build(BuildContext context) {
  73. return Scaffold(
  74. appBar: AppBar(title: const Text('Details Screen')),
  75. body: Center(
  76. child: Column(
  77. mainAxisAlignment: MainAxisAlignment.center,
  78. children: <ElevatedButton>[
  79. ElevatedButton(
  80. onPressed: () => context.go('/'),
  81. child: const Text('Go back to the Home screen'),
  82. ),
  83. ],
  84. ),
  85. ),
  86. );
  87. }
  88. }