12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- 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<RouterTable> {
- @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<String> 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<String> routeNames, Map<String, Page> page) {
- String field = "";
- routeNames.forEach((e) {
- field += "static final ${e} = \"${page[e].path}\";\n";
- });
- return field;
- }
- _generateRouterRegister(List<String> routeNames, Map<String, Page> 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;
- }
- }
|