nav.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_spinkit/flutter_spinkit.dart';
  4. import 'package:go_router/go_router.dart';
  5. import 'package:page_transition/page_transition.dart';
  6. import 'package:provider/provider.dart';
  7. import '/backend/schema/structs/index.dart';
  8. import '/auth/custom_auth/custom_auth_user_provider.dart';
  9. import '/main.dart';
  10. import '/flutter_flow/flutter_flow_theme.dart';
  11. import '/flutter_flow/lat_lng.dart';
  12. import '/flutter_flow/place.dart';
  13. import '/flutter_flow/flutter_flow_util.dart';
  14. import 'serialization_util.dart';
  15. import '/index.dart';
  16. export 'package:go_router/go_router.dart';
  17. export 'serialization_util.dart';
  18. const kTransitionInfoKey = '__transition_info__';
  19. GlobalKey<NavigatorState> appNavigatorKey = GlobalKey<NavigatorState>();
  20. const debugRouteLinkMap = {
  21. '/login':
  22. 'https://app.flutterflow.io/project/uitgaanskrant-1qhvtd?tab=uiBuilder&page=login',
  23. '/horecagelegenheidCurrent':
  24. 'https://app.flutterflow.io/project/uitgaanskrant-1qhvtd?tab=uiBuilder&page=horecagelegenheidCurrent',
  25. '/home':
  26. 'https://app.flutterflow.io/project/uitgaanskrant-1qhvtd?tab=uiBuilder&page=home',
  27. '/selectprovinciegemeente':
  28. 'https://app.flutterflow.io/project/uitgaanskrant-1qhvtd?tab=uiBuilder&page=selectprovinciegemeente',
  29. '/pUitgaanPage':
  30. 'https://app.flutterflow.io/project/uitgaanskrant-1qhvtd?tab=uiBuilder&page=PUitgaanPage',
  31. '/event':
  32. 'https://app.flutterflow.io/project/uitgaanskrant-1qhvtd?tab=uiBuilder&page=Event',
  33. '/eventCurrent':
  34. 'https://app.flutterflow.io/project/uitgaanskrant-1qhvtd?tab=uiBuilder&page=EventCurrent',
  35. '/horecagelegenhedenOverzicht':
  36. 'https://app.flutterflow.io/project/uitgaanskrant-1qhvtd?tab=uiBuilder&page=HorecagelegenhedenOverzicht',
  37. '/horecagelegenhedenOverzichtPageDataType':
  38. 'https://app.flutterflow.io/project/uitgaanskrant-1qhvtd?tab=uiBuilder&page=HorecagelegenhedenOverzichtPageDataType',
  39. '/horecagelegenhedenOverzichtSortPage':
  40. 'https://app.flutterflow.io/project/uitgaanskrant-1qhvtd?tab=uiBuilder&page=HorecagelegenhedenOverzichtSortPage'
  41. };
  42. class AppStateNotifier extends ChangeNotifier {
  43. AppStateNotifier._();
  44. static AppStateNotifier? _instance;
  45. static AppStateNotifier get instance => _instance ??= AppStateNotifier._();
  46. UitgaanskrantAuthUser? initialUser;
  47. UitgaanskrantAuthUser? user;
  48. bool showSplashImage = true;
  49. String? _redirectLocation;
  50. /// Determines whether the app will refresh and build again when a sign
  51. /// in or sign out happens. This is useful when the app is launched or
  52. /// on an unexpected logout. However, this must be turned off when we
  53. /// intend to sign in/out and then navigate or perform any actions after.
  54. /// Otherwise, this will trigger a refresh and interrupt the action(s).
  55. bool notifyOnAuthChange = true;
  56. bool get loading => user == null || showSplashImage;
  57. bool get loggedIn => user?.loggedIn ?? false;
  58. bool get initiallyLoggedIn => initialUser?.loggedIn ?? false;
  59. bool get shouldRedirect => loggedIn && _redirectLocation != null;
  60. String getRedirectLocation() => _redirectLocation!;
  61. bool hasRedirect() => _redirectLocation != null;
  62. void setRedirectLocationIfUnset(String loc) => _redirectLocation ??= loc;
  63. void clearRedirectLocation() => _redirectLocation = null;
  64. /// Mark as not needing to notify on a sign in / out when we intend
  65. /// to perform subsequent actions (such as navigation) afterwards.
  66. void updateNotifyOnAuthChange(bool notify) => notifyOnAuthChange = notify;
  67. void update(UitgaanskrantAuthUser newUser) {
  68. final shouldUpdate =
  69. user?.uid == null || newUser.uid == null || user?.uid != newUser.uid;
  70. initialUser ??= newUser;
  71. user = newUser;
  72. // Refresh the app on auth change unless explicitly marked otherwise.
  73. // No need to update unless the user has changed.
  74. if (notifyOnAuthChange && shouldUpdate) {
  75. notifyListeners();
  76. }
  77. // Once again mark the notifier as needing to update on auth change
  78. // (in order to catch sign in / out events).
  79. updateNotifyOnAuthChange(true);
  80. }
  81. void stopShowingSplashImage() {
  82. showSplashImage = false;
  83. notifyListeners();
  84. }
  85. }
  86. GoRouter createRouter(AppStateNotifier appStateNotifier) => GoRouter(
  87. initialLocation: '/',
  88. debugLogDiagnostics: true,
  89. refreshListenable: appStateNotifier,
  90. navigatorKey: appNavigatorKey,
  91. errorBuilder: (context, state) =>
  92. appStateNotifier.loggedIn ? HomeWidget() : LoginWidget(),
  93. routes: [
  94. FFRoute(
  95. name: '_initialize',
  96. path: '/',
  97. builder: (context, _) =>
  98. appStateNotifier.loggedIn ? HomeWidget() : LoginWidget(),
  99. ),
  100. FFRoute(
  101. name: LoginWidget.routeName,
  102. path: LoginWidget.routePath,
  103. builder: (context, params) => LoginWidget(),
  104. ),
  105. FFRoute(
  106. name: HorecagelegenheidCurrentWidget.routeName,
  107. path: HorecagelegenheidCurrentWidget.routePath,
  108. builder: (context, params) => HorecagelegenheidCurrentWidget(
  109. nid: params.getParam(
  110. 'nid',
  111. ParamType.String,
  112. ),
  113. ),
  114. ),
  115. FFRoute(
  116. name: HomeWidget.routeName,
  117. path: HomeWidget.routePath,
  118. builder: (context, params) => HomeWidget(),
  119. ),
  120. FFRoute(
  121. name: SelectprovinciegemeenteWidget.routeName,
  122. path: SelectprovinciegemeenteWidget.routePath,
  123. builder: (context, params) => SelectprovinciegemeenteWidget(),
  124. ),
  125. FFRoute(
  126. name: PUitgaanPageWidget.routeName,
  127. path: PUitgaanPageWidget.routePath,
  128. builder: (context, params) => PUitgaanPageWidget(
  129. plaats: params.getParam(
  130. 'plaats',
  131. ParamType.String,
  132. ),
  133. services: params.getParam(
  134. 'services',
  135. ParamType.String,
  136. ),
  137. ),
  138. ),
  139. FFRoute(
  140. name: EventWidget.routeName,
  141. path: EventWidget.routePath,
  142. builder: (context, params) => EventWidget(
  143. nid: params.getParam(
  144. 'nid',
  145. ParamType.String,
  146. ),
  147. ),
  148. ),
  149. FFRoute(
  150. name: EventCurrentWidget.routeName,
  151. path: EventCurrentWidget.routePath,
  152. builder: (context, params) => EventCurrentWidget(
  153. nid: params.getParam(
  154. 'nid',
  155. ParamType.String,
  156. ),
  157. horecaid: params.getParam(
  158. 'horecaid',
  159. ParamType.String,
  160. ),
  161. ),
  162. ),
  163. FFRoute(
  164. name: HorecagelegenhedenOverzichtWidget.routeName,
  165. path: HorecagelegenhedenOverzichtWidget.routePath,
  166. builder: (context, params) => HorecagelegenhedenOverzichtWidget(
  167. plaats: params.getParam(
  168. 'plaats',
  169. ParamType.String,
  170. ),
  171. ),
  172. ),
  173. FFRoute(
  174. name: HorecagelegenhedenOverzichtPageDataTypeWidget.routeName,
  175. path: HorecagelegenhedenOverzichtPageDataTypeWidget.routePath,
  176. builder: (context, params) =>
  177. HorecagelegenhedenOverzichtPageDataTypeWidget(
  178. plaats: params.getParam(
  179. 'plaats',
  180. ParamType.String,
  181. ),
  182. ),
  183. ),
  184. FFRoute(
  185. name: HorecagelegenhedenOverzichtSortPageWidget.routeName,
  186. path: HorecagelegenhedenOverzichtSortPageWidget.routePath,
  187. builder: (context, params) =>
  188. HorecagelegenhedenOverzichtSortPageWidget(
  189. plaats: params.getParam(
  190. 'plaats',
  191. ParamType.String,
  192. ),
  193. ),
  194. )
  195. ].map((r) => r.toRoute(appStateNotifier)).toList(),
  196. observers: [routeObserver],
  197. );
  198. extension NavParamExtensions on Map<String, String?> {
  199. Map<String, String> get withoutNulls => Map.fromEntries(
  200. entries
  201. .where((e) => e.value != null)
  202. .map((e) => MapEntry(e.key, e.value!)),
  203. );
  204. }
  205. extension NavigationExtensions on BuildContext {
  206. void goNamedAuth(
  207. String name,
  208. bool mounted, {
  209. Map<String, String> pathParameters = const <String, String>{},
  210. Map<String, String> queryParameters = const <String, String>{},
  211. Object? extra,
  212. bool ignoreRedirect = false,
  213. }) =>
  214. !mounted || GoRouter.of(this).shouldRedirect(ignoreRedirect)
  215. ? null
  216. : goNamed(
  217. name,
  218. pathParameters: pathParameters,
  219. queryParameters: queryParameters,
  220. extra: extra,
  221. );
  222. void pushNamedAuth(
  223. String name,
  224. bool mounted, {
  225. Map<String, String> pathParameters = const <String, String>{},
  226. Map<String, String> queryParameters = const <String, String>{},
  227. Object? extra,
  228. bool ignoreRedirect = false,
  229. }) =>
  230. !mounted || GoRouter.of(this).shouldRedirect(ignoreRedirect)
  231. ? null
  232. : pushNamed(
  233. name,
  234. pathParameters: pathParameters,
  235. queryParameters: queryParameters,
  236. extra: extra,
  237. );
  238. void safePop() {
  239. // If there is only one route on the stack, navigate to the initial
  240. // page instead of popping.
  241. if (canPop()) {
  242. pop();
  243. } else {
  244. go('/');
  245. }
  246. }
  247. }
  248. extension GoRouterExtensions on GoRouter {
  249. AppStateNotifier get appState => AppStateNotifier.instance;
  250. void prepareAuthEvent([bool ignoreRedirect = false]) =>
  251. appState.hasRedirect() && !ignoreRedirect
  252. ? null
  253. : appState.updateNotifyOnAuthChange(false);
  254. bool shouldRedirect(bool ignoreRedirect) =>
  255. !ignoreRedirect && appState.hasRedirect();
  256. void clearRedirectLocation() => appState.clearRedirectLocation();
  257. void setRedirectLocationIfUnset(String location) =>
  258. appState.updateNotifyOnAuthChange(false);
  259. }
  260. extension _GoRouterStateExtensions on GoRouterState {
  261. Map<String, dynamic> get extraMap =>
  262. extra != null ? extra as Map<String, dynamic> : {};
  263. Map<String, dynamic> get allParams => <String, dynamic>{}
  264. ..addAll(pathParameters)
  265. ..addAll(uri.queryParameters)
  266. ..addAll(extraMap);
  267. TransitionInfo get transitionInfo => extraMap.containsKey(kTransitionInfoKey)
  268. ? extraMap[kTransitionInfoKey] as TransitionInfo
  269. : TransitionInfo.appDefault();
  270. }
  271. class FFParameters {
  272. FFParameters(this.state, [this.asyncParams = const {}]);
  273. final GoRouterState state;
  274. final Map<String, Future<dynamic> Function(String)> asyncParams;
  275. Map<String, dynamic> futureParamValues = {};
  276. // Parameters are empty if the params map is empty or if the only parameter
  277. // present is the special extra parameter reserved for the transition info.
  278. bool get isEmpty =>
  279. state.allParams.isEmpty ||
  280. (state.allParams.length == 1 &&
  281. state.extraMap.containsKey(kTransitionInfoKey));
  282. bool isAsyncParam(MapEntry<String, dynamic> param) =>
  283. asyncParams.containsKey(param.key) && param.value is String;
  284. bool get hasFutures => state.allParams.entries.any(isAsyncParam);
  285. Future<bool> completeFutures() => Future.wait(
  286. state.allParams.entries.where(isAsyncParam).map(
  287. (param) async {
  288. final doc = await asyncParams[param.key]!(param.value)
  289. .onError((_, __) => null);
  290. if (doc != null) {
  291. futureParamValues[param.key] = doc;
  292. return true;
  293. }
  294. return false;
  295. },
  296. ),
  297. ).onError((_, __) => [false]).then((v) => v.every((e) => e));
  298. dynamic getParam<T>(
  299. String paramName,
  300. ParamType type, {
  301. bool isList = false,
  302. StructBuilder<T>? structBuilder,
  303. }) {
  304. if (futureParamValues.containsKey(paramName)) {
  305. return futureParamValues[paramName];
  306. }
  307. if (!state.allParams.containsKey(paramName)) {
  308. return null;
  309. }
  310. final param = state.allParams[paramName];
  311. // Got parameter from `extras`, so just directly return it.
  312. if (param is! String) {
  313. return param;
  314. }
  315. // Return serialized value.
  316. return deserializeParam<T>(
  317. param,
  318. type,
  319. isList,
  320. structBuilder: structBuilder,
  321. );
  322. }
  323. }
  324. class FFRoute {
  325. const FFRoute({
  326. required this.name,
  327. required this.path,
  328. required this.builder,
  329. this.requireAuth = false,
  330. this.asyncParams = const {},
  331. this.routes = const [],
  332. });
  333. final String name;
  334. final String path;
  335. final bool requireAuth;
  336. final Map<String, Future<dynamic> Function(String)> asyncParams;
  337. final Widget Function(BuildContext, FFParameters) builder;
  338. final List<GoRoute> routes;
  339. GoRoute toRoute(AppStateNotifier appStateNotifier) => GoRoute(
  340. name: name,
  341. path: path,
  342. redirect: (context, state) {
  343. if (appStateNotifier.shouldRedirect) {
  344. final redirectLocation = appStateNotifier.getRedirectLocation();
  345. appStateNotifier.clearRedirectLocation();
  346. return redirectLocation;
  347. }
  348. if (requireAuth && !appStateNotifier.loggedIn) {
  349. appStateNotifier.setRedirectLocationIfUnset(state.uri.toString());
  350. return '/login';
  351. }
  352. return null;
  353. },
  354. pageBuilder: (context, state) {
  355. fixStatusBarOniOS16AndBelow(context);
  356. final ffParams = FFParameters(state, asyncParams);
  357. final page = ffParams.hasFutures
  358. ? FutureBuilder(
  359. future: ffParams.completeFutures(),
  360. builder: (context, _) => builder(context, ffParams),
  361. )
  362. : builder(context, ffParams);
  363. final child = appStateNotifier.loading
  364. ? Center(
  365. child: SizedBox(
  366. width: 80.0,
  367. height: 80.0,
  368. child: SpinKitFadingCircle(
  369. color: Color(0xFFB1061E),
  370. size: 80.0,
  371. ),
  372. ),
  373. )
  374. : page;
  375. final transitionInfo = state.transitionInfo;
  376. return transitionInfo.hasTransition
  377. ? CustomTransitionPage(
  378. key: state.pageKey,
  379. name: state.name,
  380. child: child,
  381. transitionDuration: transitionInfo.duration,
  382. transitionsBuilder:
  383. (context, animation, secondaryAnimation, child) =>
  384. PageTransition(
  385. type: transitionInfo.transitionType,
  386. duration: transitionInfo.duration,
  387. reverseDuration: transitionInfo.duration,
  388. alignment: transitionInfo.alignment,
  389. child: child,
  390. ).buildTransitions(
  391. context,
  392. animation,
  393. secondaryAnimation,
  394. child,
  395. ),
  396. )
  397. : MaterialPage(
  398. key: state.pageKey, name: state.name, child: child);
  399. },
  400. routes: routes,
  401. );
  402. }
  403. class TransitionInfo {
  404. const TransitionInfo({
  405. required this.hasTransition,
  406. this.transitionType = PageTransitionType.fade,
  407. this.duration = const Duration(milliseconds: 300),
  408. this.alignment,
  409. });
  410. final bool hasTransition;
  411. final PageTransitionType transitionType;
  412. final Duration duration;
  413. final Alignment? alignment;
  414. static TransitionInfo appDefault() => TransitionInfo(hasTransition: false);
  415. }
  416. class RootPageContext {
  417. const RootPageContext(this.isRootPage, [this.errorRoute]);
  418. final bool isRootPage;
  419. final String? errorRoute;
  420. static bool isInactiveRootPage(BuildContext context) {
  421. final rootPageContext = context.read<RootPageContext?>();
  422. final isRootPage = rootPageContext?.isRootPage ?? false;
  423. final location = GoRouterState.of(context).uri.toString();
  424. return isRootPage &&
  425. location != '/' &&
  426. location != rootPageContext?.errorRoute;
  427. }
  428. static Widget wrap(Widget child, {String? errorRoute}) => Provider.value(
  429. value: RootPageContext(true, errorRoute),
  430. child: child,
  431. );
  432. }
  433. extension GoRouterLocationExtension on GoRouter {
  434. String getCurrentLocation() {
  435. final RouteMatch lastMatch = routerDelegate.currentConfiguration.last;
  436. final RouteMatchList matchList = lastMatch is ImperativeRouteMatch
  437. ? lastMatch.matches
  438. : routerDelegate.currentConfiguration;
  439. return matchList.uri.toString();
  440. }
  441. }