diff --git a/auto_route/example/lib/mobile/router/router.dart b/auto_route/example/lib/mobile/router/router.dart index d3495881..23e19069 100644 --- a/auto_route/example/lib/mobile/router/router.dart +++ b/auto_route/example/lib/mobile/router/router.dart @@ -3,7 +3,6 @@ import 'package:auto_route/auto_route.dart'; import 'package:example/mobile/router/router.gr.dart'; import 'package:example/mobile/screens/profile/routes.dart'; - @AutoRouterConfig(generateForDir: ['lib/mobile']) class AppRouter extends RootStackRouter { @override @@ -45,5 +44,3 @@ class AppRouter extends RootStackRouter { final BooksTab = EmptyShellRoute('BooksTab'); final ProfileTab = EmptyShellRoute('ProfileTab'); - - diff --git a/auto_route/example/lib/web_demo/router/web_router.dart b/auto_route/example/lib/web_demo/router/web_router.dart index 2a4c361d..651c130a 100644 --- a/auto_route/example/lib/web_demo/router/web_router.dart +++ b/auto_route/example/lib/web_demo/router/web_router.dart @@ -66,7 +66,6 @@ class WebAppRouter extends RootStackRouter { ]; } - @RoutePage() class MainWebPage extends StatefulWidget { final VoidCallback? navigate, showUserPosts; diff --git a/auto_route/example/lib/web_demo/web_main.dart b/auto_route/example/lib/web_demo/web_main.dart index a32d5e25..61996f22 100644 --- a/auto_route/example/lib/web_demo/web_main.dart +++ b/auto_route/example/lib/web_demo/web_main.dart @@ -21,7 +21,7 @@ class AppState extends State { setState(() {}); }); - late final _router = WebAppRouter( authService); + late final _router = WebAppRouter(authService); @override Widget build(BuildContext context) { return MaterialApp.router( diff --git a/auto_route/lib/src/route/page_route_info.dart b/auto_route/lib/src/route/page_route_info.dart index 54e77da6..695e6502 100644 --- a/auto_route/lib/src/route/page_route_info.dart +++ b/auto_route/lib/src/route/page_route_info.dart @@ -195,11 +195,9 @@ class PageRouteInfo { const ListEquality().hash(initialChildren); } - /// A proxy Route page that provides a way to create a [PageRouteInfo] /// without the need for creating a new Page Widget class EmptyShellRoute { - /// Page name final String name; diff --git a/auto_route/lib/src/router/auto_route_page.dart b/auto_route/lib/src/router/auto_route_page.dart index 71a83529..76551030 100644 --- a/auto_route/lib/src/router/auto_route_page.dart +++ b/auto_route/lib/src/router/auto_route_page.dart @@ -38,7 +38,9 @@ class AutoRoutePage extends Page { /// The pop completer that's used in navigation actions /// e.g [StackRouter.push] /// it completes when the built route is popped - Future get popped => routeData.router.ignorePopCompleters ? SynchronousFuture(null) : _popCompleter.future; + Future get popped => routeData.router.ignorePopCompleters + ? SynchronousFuture(null) + : _popCompleter.future; /// The widget passed to the route Widget get child => _child; @@ -47,7 +49,9 @@ class AutoRoutePage extends Page { AutoRoutePage({ required this.routeData, required Widget child, - }) : _child = child is AutoRouteWrapper ? WrappedRoute(child: child as AutoRouteWrapper) : child, + }) : _child = child is AutoRouteWrapper + ? WrappedRoute(child: child as AutoRouteWrapper) + : child, super( restorationId: routeData.restorationId, name: routeData.name, @@ -89,7 +93,8 @@ class AutoRoutePage extends Page { } else if (type is AdaptiveRouteType) { if (kIsWeb) { return _NoAnimationPageRouteBuilder(page: this); - } else if ([TargetPlatform.macOS, TargetPlatform.iOS].contains(defaultTargetPlatform)) { + } else if ([TargetPlatform.macOS, TargetPlatform.iOS] + .contains(defaultTargetPlatform)) { return _PageBasedCupertinoPageRoute(page: this, title: title); } } @@ -105,7 +110,8 @@ class AutoRoutePage extends Page { } } -class _PageBasedMaterialPageRoute extends PageRoute with MaterialRouteTransitionMixin { +class _PageBasedMaterialPageRoute extends PageRoute + with MaterialRouteTransitionMixin { _PageBasedMaterialPageRoute({ required AutoRoutePage page, }) : super(settings: page); @@ -145,17 +151,23 @@ class _PageBasedMaterialPageRoute extends PageRoute with MaterialRouteTran String get debugLabel => '${super.debugLabel}(${_page.name})'; @override - bool canTransitionTo(TransitionRoute nextRoute) => _canTransitionTo(nextRoute); + bool canTransitionTo(TransitionRoute nextRoute) => + _canTransitionTo(nextRoute); } bool _canTransitionTo(TransitionRoute nextRoute) { - return (nextRoute is _CustomPageBasedPageRouteBuilder && !nextRoute.fullscreenDialog || - nextRoute is MaterialRouteTransitionMixin && !nextRoute.fullscreenDialog) || - (nextRoute is _NoAnimationPageRouteTransitionMixin && !nextRoute.fullscreenDialog) || - (nextRoute is CupertinoRouteTransitionMixin && !nextRoute.fullscreenDialog); + return (nextRoute is _CustomPageBasedPageRouteBuilder && + !nextRoute.fullscreenDialog || + nextRoute is MaterialRouteTransitionMixin && + !nextRoute.fullscreenDialog) || + (nextRoute is _NoAnimationPageRouteTransitionMixin && + !nextRoute.fullscreenDialog) || + (nextRoute is CupertinoRouteTransitionMixin && + !nextRoute.fullscreenDialog); } -class _CustomPageBasedPageRouteBuilder extends PageRoute with _CustomPageRouteTransitionMixin { +class _CustomPageBasedPageRouteBuilder extends PageRoute + with _CustomPageRouteTransitionMixin { _CustomPageBasedPageRouteBuilder({ required AutoRoutePage page, required this.routeType, @@ -180,10 +192,12 @@ class _CustomPageBasedPageRouteBuilder extends PageRoute with _CustomPageR String get debugLabel => '${super.debugLabel}(${_page.name})'; @override - bool canTransitionTo(TransitionRoute nextRoute) => _canTransitionTo(nextRoute); + bool canTransitionTo(TransitionRoute nextRoute) => + _canTransitionTo(nextRoute); } -class _NoAnimationPageRouteBuilder extends PageRoute with _NoAnimationPageRouteTransitionMixin { +class _NoAnimationPageRouteBuilder extends PageRoute + with _NoAnimationPageRouteTransitionMixin { _NoAnimationPageRouteBuilder({ required AutoRoutePage page, }) : super(settings: page); @@ -207,7 +221,8 @@ class _NoAnimationPageRouteBuilder extends PageRoute with _NoAnimationPage Duration get transitionDuration => Duration.zero; @override - bool canTransitionTo(TransitionRoute nextRoute) => _canTransitionTo(nextRoute); + bool canTransitionTo(TransitionRoute nextRoute) => + _canTransitionTo(nextRoute); } mixin _NoAnimationPageRouteTransitionMixin on PageRoute { @@ -229,7 +244,8 @@ mixin _NoAnimationPageRouteTransitionMixin on PageRoute { bool get opaque => _page.opaque; @override - bool canTransitionTo(TransitionRoute nextRoute) => _canTransitionTo(nextRoute); + bool canTransitionTo(TransitionRoute nextRoute) => + _canTransitionTo(nextRoute); @override Widget buildPage( @@ -277,7 +293,8 @@ mixin _CustomPageRouteTransitionMixin on PageRoute { bool get opaque => routeType.opaque; @override - bool canTransitionTo(TransitionRoute nextRoute) => _canTransitionTo(nextRoute); + bool canTransitionTo(TransitionRoute nextRoute) => + _canTransitionTo(nextRoute); @override Widget buildPage( @@ -293,20 +310,26 @@ mixin _CustomPageRouteTransitionMixin on PageRoute { } Widget _defaultTransitionsBuilder( - BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child) { return child; } @override - Widget buildTransitions( - BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { - final transitionsBuilder = routeType.transitionsBuilder ?? _defaultTransitionsBuilder; + Widget buildTransitions(BuildContext context, Animation animation, + Animation secondaryAnimation, Widget child) { + final transitionsBuilder = + routeType.transitionsBuilder ?? _defaultTransitionsBuilder; return transitionsBuilder(context, animation, secondaryAnimation, child); } } class _PageBasedCupertinoPageRoute extends PageRoute - with CupertinoRouteTransitionMixin, CupertinoRouteTransitionOverrideMixin { + with + CupertinoRouteTransitionMixin, + CupertinoRouteTransitionOverrideMixin { _PageBasedCupertinoPageRoute({ required AutoRoutePage page, this.title, diff --git a/auto_route/lib/src/router/widgets/custom_cupertino_transitions_builder.dart b/auto_route/lib/src/router/widgets/custom_cupertino_transitions_builder.dart index b5461f3f..bcbd7132 100644 --- a/auto_route/lib/src/router/widgets/custom_cupertino_transitions_builder.dart +++ b/auto_route/lib/src/router/widgets/custom_cupertino_transitions_builder.dart @@ -503,9 +503,8 @@ class _CupertinoEdgeShadowDecoration extends Decoration { assert(bColors != null || aColors != null); // If it ever becomes necessary, we could allow decorations with different // length' here, similarly to how it is handled in [LinearGradient.lerp]. - assert(bColors == null || - aColors == null || - aColors.length == bColors.length); + assert( + bColors == null || aColors == null || aColors.length == bColors.length); return _CupertinoEdgeShadowDecoration._( [ for (int i = 0; i < bColors!.length; i += 1) diff --git a/auto_route_generator/lib/src/builders/auto_router_builder_base.dart b/auto_route_generator/lib/src/builders/auto_router_builder_base.dart index efb54cda..181b01b6 100644 --- a/auto_route_generator/lib/src/builders/auto_router_builder_base.dart +++ b/auto_route_generator/lib/src/builders/auto_router_builder_base.dart @@ -50,11 +50,15 @@ abstract class AutoRouterBuilderBase extends CacheAwareBuilder { for (final clazz in unit.declarations .whereType() .where((e) => e.metadata.any((e) => e.name.name == annotationName))) { - final routerAnnotation = clazz.metadata.firstWhere((e) => e.name.name == annotationName); - final partDirectives = - unit.directives.whereType().fold(0, (acc, a) => acc ^ a.toSource().hashCode); - calculatedHash = - calculatedHash ^ clazz.name.toString().hashCode ^ routerAnnotation.toSource().hashCode ^ partDirectives; + final routerAnnotation = + clazz.metadata.firstWhere((e) => e.name.name == annotationName); + final partDirectives = unit.directives + .whereType() + .fold(0, (acc, a) => acc ^ a.toSource().hashCode); + calculatedHash = calculatedHash ^ + clazz.name.toString().hashCode ^ + routerAnnotation.toSource().hashCode ^ + partDirectives; } return calculatedHash; } @@ -68,7 +72,8 @@ abstract class AutoRouterBuilderBase extends CacheAwareBuilder { } @override - Future onGenerateContent(BuildStep buildStep, RouterConfig item) async { + Future onGenerateContent( + BuildStep buildStep, RouterConfig item) async { final generateForDir = item.generateForDir; final generatedResults = []; final routes = []; @@ -103,7 +108,8 @@ abstract class AutoRouterBuilderBase extends CacheAwareBuilder { } @override - Future onResolve(LibraryReader library, BuildStep buildStep, int stepHash) async { + Future onResolve( + LibraryReader library, BuildStep buildStep, int stepHash) async { final annotatedElements = library.annotatedWith(_typeChecker); if (annotatedElements.isEmpty) return null; final element = annotatedElements.first.element; @@ -129,7 +135,8 @@ abstract class AutoRouterBuilderBase extends CacheAwareBuilder { return router; } - void _writeRouterFile(BuildStep buildStep, RouterConfig router, {bool toCache = false}) { + void _writeRouterFile(BuildStep buildStep, RouterConfig router, + {bool toCache = false}) { final routerFile = _buildRouterFile(buildStep, toCache: toCache); if (!routerFile.existsSync()) { routerFile.createSync(recursive: true); diff --git a/auto_route_generator/lib/src/builders/cache_aware_builder.dart b/auto_route_generator/lib/src/builders/cache_aware_builder.dart index e02017b0..3c84bc67 100644 --- a/auto_route_generator/lib/src/builders/cache_aware_builder.dart +++ b/auto_route_generator/lib/src/builders/cache_aware_builder.dart @@ -22,7 +22,8 @@ abstract class CacheAwareBuilder extends Builder { bool get cacheEnabled; /// Custom ignore for file rules passed from the options - Set get ignoreForFile => options?.config['ignore_for_file']?.cast()?.toSet() ?? {}; + Set get ignoreForFile => + options?.config['ignore_for_file']?.cast()?.toSet() ?? {}; @override final Map> buildExtensions; diff --git a/auto_route_generator/lib/src/code_builder/deferred_pages_allocator.dart b/auto_route_generator/lib/src/code_builder/deferred_pages_allocator.dart index da174f00..64084d94 100644 --- a/auto_route_generator/lib/src/code_builder/deferred_pages_allocator.dart +++ b/auto_route_generator/lib/src/code_builder/deferred_pages_allocator.dart @@ -33,9 +33,11 @@ class DeferredPagesAllocator implements Allocator { Iterable get imports => _imports.keys.map( (importPath) { if (routes.isDeferred(importPath, defaultDeferredLoading)) { - return Directive.importDeferredAs(importPath, '_i${_imports[importPath]}'); + return Directive.importDeferredAs( + importPath, '_i${_imports[importPath]}'); } else { - return Directive.import(importPath, as: '_i${_imports[importPath]}'); + return Directive.import(importPath, + as: '_i${_imports[importPath]}'); } }, ); @@ -43,10 +45,12 @@ class DeferredPagesAllocator implements Allocator { extension _RouteConfigList on List { bool isDeferred(String importPath, bool defaultDeferredLoading) { - return mapRouteToDeferredType(importPath, defaultDeferredLoading) == _DeferredStatus.Deferred; + return mapRouteToDeferredType(importPath, defaultDeferredLoading) == + _DeferredStatus.Deferred; } - _DeferredStatus mapRouteToDeferredType(String importPath, bool defaultDeferredLoading) { + _DeferredStatus mapRouteToDeferredType( + String importPath, bool defaultDeferredLoading) { for (RouteConfig routeConfig in this) { if (routeConfig.pageType?.import == importPath) { return (routeConfig.deferredLoading ?? defaultDeferredLoading) diff --git a/auto_route_generator/lib/src/code_builder/library_builder.dart b/auto_route_generator/lib/src/code_builder/library_builder.dart index 54add903..7cb9230e 100644 --- a/auto_route_generator/lib/src/code_builder/library_builder.dart +++ b/auto_route_generator/lib/src/code_builder/library_builder.dart @@ -21,10 +21,11 @@ const Reference stringRefer = Reference('String'); const Reference pageRouteType = Reference('PageRouteInfo', autoRouteImport); /// Builds a list type reference of type [reference] -TypeReference listRefer(Reference reference, {bool nullable = false}) => TypeReference((b) => b - ..symbol = "List" - ..isNullable = nullable - ..types.add(reference)); +TypeReference listRefer(Reference reference, {bool nullable = false}) => + TypeReference((b) => b + ..symbol = "List" + ..isNullable = nullable + ..types.add(reference)); /// Generates the router library output String generateLibrary( @@ -38,7 +39,9 @@ String generateLibrary( ); final emitter = DartEmitter( - allocator: router.usesPartBuilder ? Allocator.none : DeferredPagesAllocator(routes, router.deferredLoading), + allocator: router.usesPartBuilder + ? Allocator.none + : DeferredPagesAllocator(routes, router.deferredLoading), orderDirectives: true, useNullSafetySyntax: true, ); @@ -51,7 +54,8 @@ String generateLibrary( for (var i = 0; i < routes.length; i++) { final route = routes[i]; - if (deferredRoutes.any((e) => e.pageType == route.pageType && route.deferredLoading != true)) { + if (deferredRoutes.any( + (e) => e.pageType == route.pageType && route.deferredLoading != true)) { routes[i] = route.copyWith(deferredLoading: true); } } diff --git a/auto_route_generator/lib/src/code_builder/route_info_builder.dart b/auto_route_generator/lib/src/code_builder/route_info_builder.dart index f8ed0b25..ef1b15fa 100644 --- a/auto_route_generator/lib/src/code_builder/route_info_builder.dart +++ b/auto_route_generator/lib/src/code_builder/route_info_builder.dart @@ -7,23 +7,29 @@ import 'library_builder.dart'; import 'package:collection/collection.dart'; /// Builds a route info class and args class for the given [RouteConfig] -List buildRouteInfoAndArgs(RouteConfig r, RouterConfig router, DartEmitter emitter) { +List buildRouteInfoAndArgs( + RouteConfig r, RouterConfig router, DartEmitter emitter) { final argsClassRefer = refer('${r.getName(router.replaceInRouteName)}Args'); final parameters = r.parameters; final fragmentParam = parameters.firstWhereOrNull((e) => e.isUrlFragment); - final nonInheritedParameters = parameters.where((p) => !p.isInheritedPathParam).toList(); + final nonInheritedParameters = + parameters.where((p) => !p.isInheritedPathParam).toList(); final pageInfoRefer = refer('PageInfo', autoRouteImport); return [ Class( (b) => b - ..docs.addAll(['/// generated route for \n/// [${r.pageType?.refer.accept(emitter).toString()}]']) + ..docs.addAll([ + '/// generated route for \n/// [${r.pageType?.refer.accept(emitter).toString()}]' + ]) ..name = r.getName(router.replaceInRouteName) ..extend = TypeReference((b) { b ..symbol = 'PageRouteInfo' ..url = autoRouteImport ..types.add( - (nonInheritedParameters.isNotEmpty) ? argsClassRefer : refer('void'), + (nonInheritedParameters.isNotEmpty) + ? argsClassRefer + : refer('void'), ); }) ..fields.addAll([ @@ -33,14 +39,16 @@ List buildRouteInfoAndArgs(RouteConfig r, RouterConfig router, DartEmitte ..name = 'name' ..static = true ..type = stringRefer - ..assignment = literalString(r.getName(router.replaceInRouteName)).code, + ..assignment = + literalString(r.getName(router.replaceInRouteName)).code, ), Field( (b) => b ..name = 'page' ..static = true ..type = pageInfoRefer - ..assignment = pageInfoRefer.newInstance([refer('name')], {'builder': _buildMethod(r, router)}).code, + ..assignment = pageInfoRefer.newInstance( + [refer('name')], {'builder': _buildMethod(r, router)}).code, ), ]) ..constructors.add( @@ -49,7 +57,8 @@ List buildRouteInfoAndArgs(RouteConfig r, RouterConfig router, DartEmitte b ..constant = parameters.isEmpty ..optionalParameters.addAll([ - ...buildArgParams(nonInheritedParameters, emitter, toThis: false), + ...buildArgParams(nonInheritedParameters, emitter, + toThis: false), Parameter((b) => b ..named = true ..name = 'children' @@ -92,7 +101,8 @@ List buildRouteInfoAndArgs(RouteConfig r, RouterConfig router, DartEmitte ), ), ), - if (fragmentParam != null) 'fragment': refer(fragmentParam.name), + if (fragmentParam != null) + 'fragment': refer(fragmentParam.name), 'initialChildren': refer('children'), }).code); }, @@ -107,7 +117,9 @@ List buildRouteInfoAndArgs(RouteConfig r, RouterConfig router, DartEmitte ...nonInheritedParameters.map((param) => Field((b) => b ..modifier = FieldModifier.final$ ..name = param.name - ..type = param is FunctionParamConfig ? param.funRefer : param.type.refer)), + ..type = param is FunctionParamConfig + ? param.funRefer + : param.type.refer)), ]) ..constructors.add( Constructor((b) => b @@ -133,7 +145,9 @@ List buildRouteInfoAndArgs(RouteConfig r, RouterConfig router, DartEmitte } /// Builds a list of [Parameter]s from the given [parameters] -Iterable buildArgParams(List parameters, DartEmitter emitter, {bool toThis = true}) { +Iterable buildArgParams( + List parameters, DartEmitter emitter, + {bool toThis = true}) { return parameters.map( (p) => Parameter( (b) { @@ -152,15 +166,19 @@ Iterable buildArgParams(List parameters, DartEmitter emi ..toThis = toThis ..required = p.isRequired || p.isPositional ..defaultTo = defaultCode; - if (!toThis) b.type = p is FunctionParamConfig ? p.funRefer : p.type.refer; + if (!toThis) + b.type = p is FunctionParamConfig ? p.funRefer : p.type.refer; }, ), ); } Expression _buildMethod(RouteConfig r, RouterConfig router) { - final useConsConstructor = r.hasConstConstructor && !(r.deferredLoading ?? router.deferredLoading); - var constructedPage = useConsConstructor ? r.pageType!.refer.constInstance([]) : _getPageInstance(r); + final useConsConstructor = + r.hasConstConstructor && !(r.deferredLoading ?? router.deferredLoading); + var constructedPage = useConsConstructor + ? r.pageType!.refer.constInstance([]) + : _getPageInstance(r); if (r.hasWrappedRoute == true) { constructedPage = refer('WrappedRoute', autoRouteImport).newInstance( @@ -174,18 +192,25 @@ Expression _buildMethod(RouteConfig r, RouterConfig router) { } final inheritedParameters = r.parameters.where((p) => p.isInheritedPathParam); - final nonInheritedParameters = r.parameters.where((p) => !p.isInheritedPathParam); + final nonInheritedParameters = + r.parameters.where((p) => !p.isInheritedPathParam); return Method( (b) => b ..requiredParameters.add( Parameter((b) => b.name = 'data'), ) ..body = Block((b) => b.statements.addAll([ - if ((!r.hasUnparsableRequiredArgs) && r.parameters.any((p) => p.isPathParam) || + if ((!r.hasUnparsableRequiredArgs) && + r.parameters.any((p) => p.isPathParam) || inheritedParameters.isNotEmpty) - declareFinal('pathParams').assign(refer('data').property('inheritedPathParams')).statement, - if (!r.hasUnparsableRequiredArgs && r.parameters.any((p) => p.isQueryParam)) - declareFinal('queryParams').assign(refer('data').property('queryParams')).statement, + declareFinal('pathParams') + .assign(refer('data').property('inheritedPathParams')) + .statement, + if (!r.hasUnparsableRequiredArgs && + r.parameters.any((p) => p.isQueryParam)) + declareFinal('queryParams') + .assign(refer('data').property('queryParams')) + .statement, if (nonInheritedParameters.isNotEmpty) declareFinal('args') .assign( @@ -195,12 +220,16 @@ Expression _buildMethod(RouteConfig r, RouterConfig router) { (b) => b ..lambda = true ..body = r.pathQueryParams.isEmpty - ? refer('${r.getName(router.replaceInRouteName)}Args').constInstance([]).code - : refer('${r.getName(router.replaceInRouteName)}Args').newInstance( + ? refer('${r.getName(router.replaceInRouteName)}Args') + .constInstance([]).code + : refer('${r.getName(router.replaceInRouteName)}Args') + .newInstance( [], Map.fromEntries( nonInheritedParameters - .where((p) => (p.isPathParam || p.isQueryParam || p.isUrlFragment)) + .where((p) => (p.isPathParam || + p.isQueryParam || + p.isUrlFragment)) .map( (p) => MapEntry( p.name, @@ -239,7 +268,9 @@ Expression _getPageInstance(RouteConfig r) { Map.fromEntries(r.namedParams.map( (p) => MapEntry( p.name, - p.isInheritedPathParam ? _getUrlPartAssignment(p) : refer('args').property(p.name), + p.isInheritedPathParam + ? _getUrlPartAssignment(p) + : refer('args').property(p.name), ), )), ); diff --git a/auto_route_generator/lib/src/models/resolved_type.dart b/auto_route_generator/lib/src/models/resolved_type.dart index 239ff97a..f614203f 100644 --- a/auto_route_generator/lib/src/models/resolved_type.dart +++ b/auto_route_generator/lib/src/models/resolved_type.dart @@ -1,4 +1,5 @@ -import 'package:code_builder/code_builder.dart' show TypeReference, RecordType, Reference; +import 'package:code_builder/code_builder.dart' + show TypeReference, RecordType, Reference; /// A class that represents a resolved type. /// @@ -61,10 +62,15 @@ class ResolvedType { ..url = import ..isNullable = isNullable ..positionalFieldTypes.addAll( - typeArguments.where((e) => !e.isNamedRecordField).map((e) => e.refer), + typeArguments + .where((e) => !e.isNamedRecordField) + .map((e) => e.refer), ) ..namedFieldTypes.addAll({ - for (final entry in [...typeArguments.where((e) => e.isNamedRecordField)]) entry.nameInRecord!: entry.refer + for (final entry in [ + ...typeArguments.where((e) => e.isNamedRecordField) + ]) + entry.nameInRecord!: entry.refer }), ); } @@ -82,7 +88,10 @@ class ResolvedType { @override bool operator ==(Object other) => - identical(this, other) || other is ResolvedType && runtimeType == other.runtimeType && identity == other.identity; + identical(this, other) || + other is ResolvedType && + runtimeType == other.runtimeType && + identity == other.identity; @override int get hashCode => import.hashCode ^ name.hashCode; @@ -95,7 +104,8 @@ class ResolvedType { 'isNullable': this.isNullable, 'isRecordType': this._isRecordType, if (nameInRecord != null) 'nameInRecord': this.nameInRecord, - if (typeArguments.isNotEmpty) 'typeArguments': this.typeArguments.map((e) => e.toJson()).toList(), + if (typeArguments.isNotEmpty) + 'typeArguments': this.typeArguments.map((e) => e.toJson()).toList(), }; } diff --git a/auto_route_generator/lib/src/models/route_config.dart b/auto_route_generator/lib/src/models/route_config.dart index 2c433b3b..92f83a0e 100644 --- a/auto_route_generator/lib/src/models/route_config.dart +++ b/auto_route_generator/lib/src/models/route_config.dart @@ -17,7 +17,6 @@ class RouteConfig { /// the class name of the route final String className; - /// the parameters of the route final List parameters; @@ -58,10 +57,12 @@ class RouteConfig { } /// Returns all the required params - Iterable get requiredParams => parameters.where((p) => p.isPositional && !p.isOptional); + Iterable get requiredParams => + parameters.where((p) => p.isPositional && !p.isOptional); /// Returns all the optional params - Iterable get positionalParams => parameters.where((p) => p.isPositional); + Iterable get positionalParams => + parameters.where((p) => p.isPositional); /// Returns all the named params Iterable get namedParams => parameters.where((p) => p.isNamed); @@ -71,7 +72,8 @@ class RouteConfig { var nameToUse; if (name != null) { nameToUse = name; - } else if (replacementInRouteName != null && replacementInRouteName.split(',').length == 2) { + } else if (replacementInRouteName != null && + replacementInRouteName.split(',').length == 2) { var parts = replacementInRouteName.split(','); nameToUse = className.replaceAll(RegExp(parts[0]), parts[1]); } else { @@ -81,8 +83,8 @@ class RouteConfig { } /// Whether this route has arguments that can't be parsed - bool get hasUnparsableRequiredArgs => - parameters.any((p) => (p.isRequired || p.isPositional) && !p.isPathParam && !p.isQueryParam); + bool get hasUnparsableRequiredArgs => parameters.any((p) => + (p.isRequired || p.isPositional) && !p.isPathParam && !p.isQueryParam); /// Clones the route config with the given parameters RouteConfig copyWith({ @@ -145,7 +147,9 @@ class RouteConfig { return RouteConfig( name: map['name'] as String?, pathParams: pathParams, - pageType: map['pageType'] == null ? null : ResolvedType.fromJson(map['pageType']), + pageType: map['pageType'] == null + ? null + : ResolvedType.fromJson(map['pageType']), className: map['className'] as String, parameters: parameters, hasWrappedRoute: map['hasWrappedRoute'] as bool?, diff --git a/auto_route_generator/lib/src/models/route_parameter_config.dart b/auto_route_generator/lib/src/models/route_parameter_config.dart index 7033e827..cdd8829a 100644 --- a/auto_route_generator/lib/src/models/route_parameter_config.dart +++ b/auto_route_generator/lib/src/models/route_parameter_config.dart @@ -47,6 +47,7 @@ class ParamConfig { /// whether the parameter is a url fragment final bool isUrlFragment; + /// whether the parameter is an inherited path param final bool isInheritedPathParam; @@ -102,7 +103,7 @@ class ParamConfig { case 'bool': return type.isNullable ? 'optBool' : 'getBool'; - case 'List' : + case 'List': return type.isNullable ? 'optList' : 'getList'; default: return 'get'; @@ -151,7 +152,6 @@ class ParamConfig { isQueryParam: map['isQueryParam'] as bool, isUrlFragment: map['isUrlFragment'] as bool, defaultValueCode: map['defaultValueCode'] as String?, - ); } } diff --git a/auto_route_generator/lib/src/models/router_config.dart b/auto_route_generator/lib/src/models/router_config.dart index 701435e2..854f3074 100644 --- a/auto_route_generator/lib/src/models/router_config.dart +++ b/auto_route_generator/lib/src/models/router_config.dart @@ -1,5 +1,3 @@ - - /// RouterConfig class RouterConfig { /// The name of the router class @@ -23,7 +21,6 @@ class RouterConfig { /// The list of directories to generate for final List generateForDir; - /// Default constructor const RouterConfig({ required this.routerClassName, diff --git a/auto_route_generator/lib/src/resolvers/route_config_resolver.dart b/auto_route_generator/lib/src/resolvers/route_config_resolver.dart index 8eaa892a..c4cedc11 100644 --- a/auto_route_generator/lib/src/resolvers/route_config_resolver.dart +++ b/auto_route_generator/lib/src/resolvers/route_config_resolver.dart @@ -25,8 +25,8 @@ class RouteConfigResolver { final classElement = element as ClassElement; final page = classElement.thisType; - final hasWrappedRoute = - classElement.allSupertypes.any((e) => e.getDisplayString(withNullability: false) == 'AutoRouteWrapper'); + final hasWrappedRoute = classElement.allSupertypes.any((e) => + e.getDisplayString(withNullability: false) == 'AutoRouteWrapper'); var pageType = _typeResolver.resolveType(page); var className = page.getDisplayString(withNullability: false); @@ -61,8 +61,10 @@ class RouteConfigResolver { var pathParameters = parameters.where((element) => element.isPathParam); if (parameters.any((p) => p.isPathParam || p.isQueryParam)) { - var unParsableRequiredArgs = - parameters.where((p) => (p.isRequired || p.isPositional) && !p.isPathParam && !p.isQueryParam); + var unParsableRequiredArgs = parameters.where((p) => + (p.isRequired || p.isPositional) && + !p.isPathParam && + !p.isQueryParam); if (unParsableRequiredArgs.isNotEmpty) { print( '\nWARNING => Because [$className] has required parameters ${unParsableRequiredArgs.map((e) => e.paramName)} ' diff --git a/auto_route_generator/lib/src/resolvers/route_parameter_resolver.dart b/auto_route_generator/lib/src/resolvers/route_parameter_resolver.dart index 4fc2f639..a054b7db 100644 --- a/auto_route_generator/lib/src/resolvers/route_parameter_resolver.dart +++ b/auto_route_generator/lib/src/resolvers/route_parameter_resolver.dart @@ -31,7 +31,8 @@ class RouteParameterResolver { var nameOrAlias = paramName; var isInheritedPathParam = false; - final isUrlFragment = _urlFragmentChecker.hasAnnotationOfExact(parameterElement); + final isUrlFragment = + _urlFragmentChecker.hasAnnotationOfExact(parameterElement); if (pathParamAnnotation != null) { isInheritedPathParam = @@ -56,12 +57,15 @@ class RouteParameterResolver { } throwIf( - [isUrlFragment, pathParamAnnotation != null, queryParamAnnotation != null].where((e) => e).length > 1, + [isUrlFragment, pathParamAnnotation != null, queryParamAnnotation != null] + .where((e) => e) + .length > + 1, '${parameterElement.name} can only be annotated with one of @PathParam, @QueryParam or @urlFragment', element: parameterElement, ); - if(isUrlFragment){ + if (isUrlFragment) { throwIf( type.name != 'String', 'UrlFragments must be of type String', @@ -88,7 +92,6 @@ class RouteParameterResolver { isQueryParam: queryParamAnnotation != null, isUrlFragment: isUrlFragment, defaultValueCode: parameterElement.defaultValueCode, - ); } diff --git a/auto_route_generator/lib/src/resolvers/router_config_resolver.dart b/auto_route_generator/lib/src/resolvers/router_config_resolver.dart index 02c07fee..dfdc6e1d 100644 --- a/auto_route_generator/lib/src/resolvers/router_config_resolver.dart +++ b/auto_route_generator/lib/src/resolvers/router_config_resolver.dart @@ -6,7 +6,6 @@ import '../models/router_config.dart'; /// Extracts and holds router configs class RouterConfigResolver { - /// Default constructor RouterConfigResolver(); @@ -18,7 +17,6 @@ class RouterConfigResolver { bool usesPartBuilder = false, int? cacheHash, }) { - final deferredLoading = autoRouter.peek('deferredLoading')?.boolValue ?? false; var replaceInRouteName = autoRouter.peek('replaceInRouteName')?.stringValue; diff --git a/auto_route_generator/lib/src/resolvers/type_resolver.dart b/auto_route_generator/lib/src/resolvers/type_resolver.dart index bd182d32..f9b8faf8 100644 --- a/auto_route_generator/lib/src/resolvers/type_resolver.dart +++ b/auto_route_generator/lib/src/resolvers/type_resolver.dart @@ -1,12 +1,13 @@ import 'package:analyzer/dart/element/element.dart'; -import 'package:analyzer/dart/element/nullability_suffix.dart' show NullabilitySuffix; +import 'package:analyzer/dart/element/nullability_suffix.dart' + show NullabilitySuffix; import 'package:analyzer/dart/element/type.dart' show DartType, ParameterizedType, RecordType; import 'package:auto_route_generator/src/models/resolved_type.dart'; import 'package:path/path.dart' as p; - const _unPreferredImports = {'dart:ui'}; + /// A Helper class that resolves types class TypeResolver { /// The list of resolved libraries in [BuildStep] @@ -25,18 +26,21 @@ class TypeResolver { return null; } - final fallBackImports = {}; + final fallBackImports = {}; for (var lib in libs) { - if (!_isCoreDartType(lib) && lib.exportNamespace.definedNames.values.contains(element)) { + if (!_isCoreDartType(lib) && + lib.exportNamespace.definedNames.values.contains(element)) { final uri = lib.source.uri; - if(_unPreferredImports.contains(uri.toString())){ + if (_unPreferredImports.contains(uri.toString())) { fallBackImports.add(uri.toString()); continue; - } + } if (uri.scheme == 'asset') { return _assetToPackage(lib.source.uri); } - return targetFile == null ? lib.identifier : _relative(uri, targetFile!); + return targetFile == null + ? lib.identifier + : _relative(uri, targetFile!); } } return fallBackImports.firstOrNull; @@ -61,12 +65,16 @@ class TypeResolver { String _relative(Uri fileUri, Uri to) { var libName = to.pathSegments.first; - if ((to.scheme == 'package' && fileUri.scheme == 'package' && fileUri.pathSegments.first == libName) || + if ((to.scheme == 'package' && + fileUri.scheme == 'package' && + fileUri.pathSegments.first == libName) || (to.scheme == 'asset' && fileUri.scheme != 'package')) { if (fileUri.path == to.path) { return fileUri.pathSegments.last; } else { - return p.posix.relative(fileUri.path, from: to.path).replaceFirst('../', ''); + return p.posix + .relative(fileUri.path, from: to.path) + .replaceFirst('../', ''); } } else { return fileUri.toString(); @@ -84,7 +92,8 @@ class TypeResolver { types.add(ResolvedType( name: recordField.type.element?.name ?? 'void', import: resolveImport(recordField.type.element), - isNullable: recordField.type.nullabilitySuffix == NullabilitySuffix.question, + isNullable: + recordField.type.nullabilitySuffix == NullabilitySuffix.question, typeArguments: _resolveTypeArguments(recordField.type), )); } @@ -92,7 +101,8 @@ class TypeResolver { types.add(ResolvedType( name: recordField.type.element?.name ?? 'void', import: resolveImport(recordField.type.element), - isNullable: recordField.type.nullabilitySuffix == NullabilitySuffix.question, + isNullable: + recordField.type.nullabilitySuffix == NullabilitySuffix.question, typeArguments: _resolveTypeArguments(recordField.type), nameInRecord: recordField.name, )); @@ -127,9 +137,9 @@ class TypeResolver { final import = resolveImport(effectiveElement); final typeArgs = []; final alias = type.alias; - if(alias != null) { - typeArgs.addAll(alias.typeArguments.map(resolveType)); - }else { + if (alias != null) { + typeArgs.addAll(alias.typeArguments.map(resolveType)); + } else { typeArgs.addAll(_resolveTypeArguments(type)); } if (type is RecordType && type.alias == null) { @@ -142,7 +152,8 @@ class TypeResolver { } return ResolvedType( - name: effectiveElement?.displayName ?? type.getDisplayString(withNullability: false), + name: effectiveElement?.displayName ?? + type.getDisplayString(withNullability: false), isNullable: type.nullabilitySuffix == NullabilitySuffix.question, import: import, typeArguments: typeArgs,