import 'package:analyzer/dart/element/element.dart'; import 'package:build/build.dart'; import 'package:router_gen/annotation/router_table.dart'; import 'package:router_gen/model/router.dart'; import 'package:source_gen/source_gen.dart'; import 'package:path/path.dart' as Path; /// generate router table class RouterTableGenerator extends GeneratorForAnnotation { @override generateForAnnotatedElement( Element element, ConstantReader annotation, BuildStep buildStep) { String path = buildStep.inputId.path; // lib/xxx.dart String relatedFileName = Path.basename(path); // xxx.dart String relatedClassName = element.name; String imports = ""; for (String import in router.imports) { imports = imports + "import '" + import + "';\n"; } // all router's name List routeNames = router.routerMap.keys.toList(); String pathFiled = _generateFields(routeNames, router.routerMap); String register = _generateRouterRegister(routeNames, router.routerMap); return """ import '${relatedFileName}'; import 'package:fluro/fluro.dart' as fluro; import 'package:school_parent/base_plugin/routes.dart'; ${imports} class \$${relatedClassName} implements ${relatedClassName} { ${pathFiled} @override void registerRoutes(fluro.Router router) { ${register} } } """; } _generateFields(List routeNames, Map page) { String field = ""; routeNames.forEach((e) { field += "static final ${e} = \"${page[e].path}\";\n"; }); return field; } _generateRouterRegister(List routeNames, Map page) { String register = ""; routeNames.forEach((e) { String params = ""; page[e].arguments.forEach((element) { params += "${element.name}: IRoutesProvider.getParams<${element.type}>(p, \"${element.name}\"),\n"; }); register += """ router.define(${e}, handler: fluro.Handler( handlerFunc: (c, p) => ${page[e].name}( ${params} ), ), ); """; }); return register; } }