fluro_router.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. * fluro
  3. * Created by Yakka
  4. * https://theyakka.com
  5. *
  6. * Copyright (c) 2019 Yakka, LLC. All rights reserved.
  7. * See LICENSE for distribution and usage details.
  8. */
  9. import 'dart:async';
  10. import 'package:fluro/fluro.dart';
  11. import 'package:fluro/src/common.dart';
  12. import 'package:flutter/foundation.dart';
  13. import 'package:flutter/cupertino.dart';
  14. import 'package:flutter/material.dart';
  15. /// {@template fluro_router}
  16. /// Attach [FluroRouter] to [MaterialApp] by connnecting [FluroRouter.generator] to [MaterialApp.onGenerateRoute].
  17. ///
  18. /// Define routes with [FluroRouter.define], optionally specifying transition types and connecting string path params to
  19. /// your screen widget's constructor.
  20. ///
  21. /// Push new route paths with [FluroRouter.appRouter.navigateTo] or continue to use [Navigator.of(context).push] if you prefer.
  22. /// {@endtemplate}
  23. class FluroRouter {
  24. /// The static / singleton instance of [FluroRouter]
  25. ///
  26. /// {@macro fluro_router}
  27. static final appRouter = FluroRouter();
  28. /// The tree structure that stores the defined routes
  29. final RouteTree _routeTree = RouteTree();
  30. /// Generic handler for when a route has not been defined
  31. Handler notFoundHandler;
  32. /// Creates a [PageRoute] definition for the passed [RouteHandler]. You can optionally provide a default transition type.
  33. void define(String routePath,
  34. {@required Handler handler,
  35. TransitionType transitionType,
  36. Duration transitionDuration = const Duration(milliseconds: 250),
  37. RouteTransitionsBuilder transitionBuilder}) {
  38. _routeTree.addRoute(
  39. AppRoute(routePath, handler,
  40. transitionType: transitionType,
  41. transitionDuration: transitionDuration,
  42. transitionBuilder: transitionBuilder),
  43. );
  44. }
  45. /// Finds a defined [AppRoute] for the path value. If no [AppRoute] definition was found
  46. /// then function will return null.
  47. AppRouteMatch match(String path) {
  48. return _routeTree.matchRoute(path);
  49. }
  50. /// Similar to [Navigator.pop]
  51. void pop<T>(BuildContext context, [T result]) =>
  52. Navigator.of(context).pop(result);
  53. /// Similar to [Navigator.push] but with a few extra features.
  54. Future navigateTo(BuildContext context, String path,
  55. {bool replace = false,
  56. bool clearStack = false,
  57. bool maintainState = true,
  58. bool rootNavigator = false,
  59. TransitionType transition,
  60. Duration transitionDuration,
  61. RouteTransitionsBuilder transitionBuilder,
  62. RouteSettings routeSettings}) {
  63. RouteMatch routeMatch = matchRoute(context, path,
  64. transitionType: transition,
  65. transitionsBuilder: transitionBuilder,
  66. transitionDuration: transitionDuration,
  67. maintainState: maintainState,
  68. routeSettings: routeSettings);
  69. Route<dynamic> route = routeMatch.route;
  70. Completer completer = Completer();
  71. Future future = completer.future;
  72. if (routeMatch.matchType == RouteMatchType.nonVisual) {
  73. completer.complete("Non visual route type.");
  74. } else {
  75. if (route == null && notFoundHandler != null) {
  76. route = _notFoundRoute(context, path, maintainState: maintainState);
  77. }
  78. if (route != null) {
  79. final navigator =
  80. Navigator.of(context, rootNavigator: rootNavigator);
  81. if (clearStack) {
  82. future = navigator.pushAndRemoveUntil(route, (check) => false);
  83. } else {
  84. future = replace
  85. ? navigator.pushReplacement(route)
  86. : navigator.push(route);
  87. }
  88. completer.complete();
  89. } else {
  90. String error = "No registered route was found to handle '$path'.";
  91. print(error);
  92. completer.completeError(RouteNotFoundException(error, path));
  93. }
  94. }
  95. return future;
  96. }
  97. Route<Null> _notFoundRoute(BuildContext context, String path,
  98. {bool maintainState}) {
  99. RouteCreator<Null> creator =
  100. (RouteSettings routeSettings, Map<String, List<String>> parameters) {
  101. return MaterialPageRoute<Null>(
  102. settings: routeSettings,
  103. maintainState: maintainState,
  104. builder: (BuildContext context) {
  105. return notFoundHandler.handlerFunc(context, parameters);
  106. });
  107. };
  108. return creator(RouteSettings(name: path), null);
  109. }
  110. /// Attempt to match a route to the provided [path].
  111. RouteMatch matchRoute(BuildContext buildContext, String path,
  112. {RouteSettings routeSettings,
  113. TransitionType transitionType,
  114. Duration transitionDuration,
  115. RouteTransitionsBuilder transitionsBuilder,
  116. bool maintainState = true}) {
  117. RouteSettings settingsToUse = routeSettings;
  118. if (routeSettings == null) {
  119. settingsToUse = RouteSettings(name: path);
  120. }
  121. if (settingsToUse.name == null) {
  122. settingsToUse = settingsToUse.copyWith(name: path);
  123. }
  124. AppRouteMatch match = _routeTree.matchRoute(path);
  125. AppRoute route = match?.route;
  126. if (route?.transitionDuration != null) {
  127. transitionDuration = route?.transitionDuration;
  128. }
  129. Handler handler = (route != null ? route?.handler : notFoundHandler);
  130. var transition = transitionType;
  131. if (transitionType == null) {
  132. transition =
  133. route != null ? route?.transitionType : TransitionType.native;
  134. }
  135. if (route == null && notFoundHandler == null) {
  136. return RouteMatch(
  137. matchType: RouteMatchType.noMatch,
  138. errorMessage: "No matching route was found");
  139. }
  140. Map<String, List<String>> parameters =
  141. match?.parameters ?? <String, List<String>>{};
  142. if (handler.type == HandlerType.function) {
  143. handler.handlerFunc(buildContext, parameters);
  144. return RouteMatch(matchType: RouteMatchType.nonVisual);
  145. }
  146. RouteCreator creator =
  147. (RouteSettings routeSettings, Map<String, List<String>> parameters) {
  148. bool isNativeTransition = (transition == TransitionType.native ||
  149. transition == TransitionType.nativeModal);
  150. if (isNativeTransition) {
  151. return MaterialPageRoute<dynamic>(
  152. settings: routeSettings,
  153. fullscreenDialog: transition == TransitionType.nativeModal,
  154. maintainState: maintainState,
  155. builder: (BuildContext context) {
  156. return handler.handlerFunc(context, parameters);
  157. });
  158. } else if (transition == TransitionType.material ||
  159. transition == TransitionType.materialFullScreenDialog) {
  160. return MaterialPageRoute<dynamic>(
  161. settings: routeSettings,
  162. fullscreenDialog:
  163. transition == TransitionType.materialFullScreenDialog,
  164. maintainState: maintainState,
  165. builder: (BuildContext context) {
  166. return handler.handlerFunc(context, parameters);
  167. });
  168. } else if (transition == TransitionType.cupertino ||
  169. transition == TransitionType.cupertinoFullScreenDialog) {
  170. return CupertinoPageRoute<dynamic>(
  171. settings: routeSettings,
  172. fullscreenDialog:
  173. transition == TransitionType.cupertinoFullScreenDialog,
  174. maintainState: maintainState,
  175. builder: (BuildContext context) {
  176. return handler.handlerFunc(context, parameters);
  177. });
  178. } else {
  179. var routeTransitionsBuilder;
  180. if (transition == TransitionType.custom) {
  181. routeTransitionsBuilder =
  182. transitionsBuilder ?? route?.transitionBuilder;
  183. } else {
  184. routeTransitionsBuilder = _standardTransitionsBuilder(transition);
  185. }
  186. return PageRouteBuilder<dynamic>(
  187. settings: routeSettings,
  188. maintainState: maintainState,
  189. pageBuilder: (BuildContext context, Animation<double> animation,
  190. Animation<double> secondaryAnimation) {
  191. return handler.handlerFunc(context, parameters);
  192. },
  193. transitionDuration: transition == TransitionType.none
  194. ? Duration.zero
  195. : transitionDuration ?? route?.transitionDuration,
  196. reverseTransitionDuration: transition == TransitionType.none
  197. ? Duration.zero
  198. : transitionDuration ?? route?.transitionDuration,
  199. transitionsBuilder: transition == TransitionType.none
  200. ? (_, __, ___, child) => child
  201. : routeTransitionsBuilder,
  202. );
  203. }
  204. };
  205. return RouteMatch(
  206. matchType: RouteMatchType.visual,
  207. route: creator(settingsToUse, parameters),
  208. );
  209. }
  210. RouteTransitionsBuilder _standardTransitionsBuilder(
  211. TransitionType transitionType) {
  212. return (BuildContext context, Animation<double> animation,
  213. Animation<double> secondaryAnimation, Widget child) {
  214. if (transitionType == TransitionType.fadeIn) {
  215. return FadeTransition(opacity: animation, child: child);
  216. } else {
  217. const Offset topLeft = const Offset(0.0, 0.0);
  218. const Offset topRight = const Offset(1.0, 0.0);
  219. const Offset bottomLeft = const Offset(0.0, 1.0);
  220. Offset startOffset = bottomLeft;
  221. Offset endOffset = topLeft;
  222. if (transitionType == TransitionType.inFromLeft) {
  223. startOffset = const Offset(-1.0, 0.0);
  224. endOffset = topLeft;
  225. } else if (transitionType == TransitionType.inFromRight) {
  226. startOffset = topRight;
  227. endOffset = topLeft;
  228. } else if (transitionType == TransitionType.inFromBottom) {
  229. startOffset = bottomLeft;
  230. endOffset = topLeft;
  231. } else if (transitionType == TransitionType.inFromTop) {
  232. startOffset = Offset(0.0, -1.0);
  233. endOffset = topLeft;
  234. }
  235. return SlideTransition(
  236. position: Tween<Offset>(
  237. begin: startOffset,
  238. end: endOffset,
  239. ).animate(animation),
  240. child: child,
  241. );
  242. }
  243. };
  244. }
  245. /// Route generation method. This function can be used as a way to create routes on-the-fly
  246. /// if any defined handler is found. It can also be used with the [MaterialApp.onGenerateRoute]
  247. /// property as callback to create routes that can be used with the [Navigator] class.
  248. Route<dynamic> generator(RouteSettings routeSettings) {
  249. RouteMatch match =
  250. matchRoute(null, routeSettings.name, routeSettings: routeSettings);
  251. return match.route;
  252. }
  253. /// Prints the route tree so you can analyze it.
  254. void printTree() {
  255. _routeTree.printTree();
  256. }
  257. }