This repository has been archived by the owner on Jun 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
main_router.dart
227 lines (194 loc) · 6.04 KB
/
main_router.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'router/details_screen.dart';
import 'router/main_screen.dart';
import 'router/unknown_screen.dart';
void main() {
runApp(TheApp());
}
class TheApp extends StatelessWidget {
TheApp();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Flutter Router Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
routerDelegate: TheAppRouterDelegate(),
routeInformationParser: TheAppRouteInformationParser(),
);
}
}
/// A delegate that is used by the [Router] widget to build and configure a
/// navigating widget.
///
/// This delegate is the core piece of the [Router] widget. It responds to
/// push route and pop route intent from the engine and notifies the [Router]
/// to rebuild. It also act as a builder for the [Router] widget and builds a
/// navigating widget, typically a [Navigator], when the [Router] widget
/// builds.
class TheAppRouterDelegate extends RouterDelegate<TheAppPath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<TheAppPath> {
TheAppRouterDelegate() {
// This part is important because we pass the notification
// from RoutePageManager to RouterDelegate. This way our navigation
// changes (e.g. pushes) will be reflected in the address bar
pageManager.addListener(notifyListeners);
}
final RoutePageManager pageManager = RoutePageManager();
/// In the build method we need to return Navigator using [navigatorKey]
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<RoutePageManager>.value(
value: pageManager,
child: Consumer<RoutePageManager>(
builder: (context, pageManager, child) {
return Navigator(
key: navigatorKey,
onPopPage: _onPopPage,
pages: List.of(pageManager.pages),
);
},
),
);
}
bool _onPopPage(Route<dynamic> route, dynamic result) {
final didPop = route.didPop(result);
if (!didPop) {
return false;
}
/// Notify the PageManager that page was popped
pageManager.didPop(route.settings);
return true;
}
@override
GlobalKey<NavigatorState> get navigatorKey => pageManager.navigatorKey;
@override
TheAppPath get currentConfiguration => pageManager.currentPath;
@override
Future<void> setNewRoutePath(TheAppPath configuration) async {
await pageManager.setNewRoutePath(configuration);
}
}
class RoutePageManager extends ChangeNotifier {
static RoutePageManager of(BuildContext context) {
return Provider.of<RoutePageManager>(context, listen: false);
}
/// Here we are storing the current list of pages
List<Page> get pages => List.unmodifiable(_pages);
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
final List<Page> _pages = [
MaterialPage(
child: MainScreen(),
key: const Key('MainScreen'),
name: '/',
),
];
TheAppPath get currentPath {
return parseRoute(Uri.parse(_pages.last.name));
}
void didPop(Page page) {
_pages.remove(page);
notifyListeners();
}
/// This is where we handle new route information and manage the pages list
Future<void> setNewRoutePath(TheAppPath configuration) async {
if (configuration.isUnknown) {
// Handling 404
_pages.add(
MaterialPage(
child: UnknownScreen(),
key: UniqueKey(),
name: '/404',
),
);
} else if (configuration.isDetailsPage) {
// Handling details screens
_pages.add(
MaterialPage(
child: DetailsScreen(id: configuration.id),
key: UniqueKey(),
name: '/details/${configuration.id}',
),
);
} else if (configuration.isHomePage) {
// Restoring to MainScreen
_pages.removeWhere(
(element) => element.key != const Key('MainScreen'),
);
}
notifyListeners();
return;
}
void openDetails() {
setNewRoutePath(TheAppPath.details(_pages.length));
}
void resetToHome() {
setNewRoutePath(TheAppPath.home());
}
void addDetailsBelow() {
_pages.insert(
_pages.length - 1,
MaterialPage(
child: DetailsScreen(id: _pages.length),
key: UniqueKey(),
name: '/details/${_pages.length}',
),
);
notifyListeners();
}
}
TheAppPath parseRoute(Uri uri) {
// Handle '/'
if (uri.pathSegments.isEmpty) {
return TheAppPath.home();
}
// Handle '/details/:id'
if (uri.pathSegments.length == 2) {
if (uri.pathSegments[0] != 'details') return TheAppPath.unknown();
var remaining = uri.pathSegments[1];
var id = int.tryParse(remaining);
if (id == null) return TheAppPath.unknown();
return TheAppPath.details(id);
}
// Handle unknown routes
return TheAppPath.unknown();
}
/// Parser inspired by https://github.com/acoutts/flutter_nav_2.0_mobx/blob/master/lib/main.dart
///
/// Using typed information instead of string allows for greater flexibility
class TheAppRouteInformationParser extends RouteInformationParser<TheAppPath> {
@override
Future<TheAppPath> parseRouteInformation(
RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location);
return parseRoute(uri);
}
@override
RouteInformation restoreRouteInformation(TheAppPath path) {
if (path.isUnknown) {
return RouteInformation(location: '/404');
}
if (path.isHomePage) {
return RouteInformation(location: '/');
}
if (path.isDetailsPage) {
return RouteInformation(location: '/details/${path.id}');
}
return null;
}
}
/// Class responsible for storing typed information about
/// the current navigation path in the app
class TheAppPath {
final int id;
TheAppPath.home() : id = null;
TheAppPath.details(this.id);
TheAppPath.unknown() : id = -1;
bool get isHomePage => id == null;
bool get isDetailsPage => id != null;
bool get isUnknown => id == -1;
}