router_table_generator.dart 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import 'package:analyzer/dart/element/element.dart';
  2. import 'package:build/build.dart';
  3. import 'package:router_gen/annotation/router_table.dart';
  4. import 'package:router_gen/model/router.dart';
  5. import 'package:source_gen/source_gen.dart';
  6. import 'package:path/path.dart' as Path;
  7. /// generate router table
  8. class RouterTableGenerator extends GeneratorForAnnotation<RouterTable> {
  9. @override
  10. generateForAnnotatedElement(
  11. Element element, ConstantReader annotation, BuildStep buildStep) {
  12. String path = buildStep.inputId.path; // lib/xxx.dart
  13. String relatedFileName = Path.basename(path); // xxx.dart
  14. String relatedClassName = element.name;
  15. String imports = "";
  16. for (String import in router.imports) {
  17. imports = imports + "import '" + import + "';\n";
  18. }
  19. // all router's name
  20. List<String> routeNames = router.routerMap.keys.toList();
  21. String pathFiled = _generateFields(routeNames, router.routerMap);
  22. String register = _generateRouterRegister(routeNames, router.routerMap);
  23. return """
  24. import '${relatedFileName}';
  25. import 'package:fluro/fluro.dart' as fluro;
  26. import 'package:school_parent/base_plugin/routes.dart';
  27. ${imports}
  28. class \$${relatedClassName} implements ${relatedClassName} {
  29. ${pathFiled}
  30. @override
  31. void registerRoutes(fluro.Router router) {
  32. ${register}
  33. }
  34. }
  35. """;
  36. }
  37. _generateFields(List<String> routeNames, Map<String, Page> page) {
  38. String field = "";
  39. routeNames.forEach((e) {
  40. field += "static final ${e} = \"${page[e].path}\";\n";
  41. });
  42. return field;
  43. }
  44. _generateRouterRegister(List<String> routeNames, Map<String, Page> page) {
  45. String register = "";
  46. routeNames.forEach((e) {
  47. String params = "";
  48. page[e].arguments.forEach((element) {
  49. params +=
  50. "${element.name}: IRoutesProvider.getParams<${element.type}>(p, \"${element.name}\"),\n";
  51. });
  52. register += """
  53. router.define(${e},
  54. handler: fluro.Handler(
  55. handlerFunc: (c, p) => ${page[e].name}(
  56. ${params}
  57. ),
  58. ),
  59. );
  60. """;
  61. });
  62. return register;
  63. }
  64. }