import 'package:analyzer/dart/element/element.dart'; import 'package:router_gen/model/router.dart'; import 'package:router_gen/util/utils.dart'; import 'package:source_gen/source_gen.dart'; /// find class path from argument class ModelImportGenerator extends Generator { static List modelImports = []; const ModelImportGenerator(); @override Future generate(LibraryReader library, _) async { if (library.classes.isNotEmpty) { Map routerMap = router.routerMap; for (String key in routerMap.keys) { Page page = routerMap[key]; for (Argument argument in page.arguments) { if (argument.isImported) continue; if (_isSpeciousType(argument.type)) { // 处理type List type = getType(argument.type); type.removeWhere((element) => _isSpeciousType(element) == false); if (type.length == 0) { continue; } // 比较class name bool isInThisClass = false; for (ClassElement element in library.classes) { if (type.contains(element.displayName)) { isInThisClass = true; break; } } // 添加import if (isInThisClass) { argument.isImported = true; router.imports.add(getImportStr(_)); } } else { argument.isImported = true; } } } } return null; } bool _isSpeciousType(String type) { if (type == "int" || type == "double" || type == "num" || type == "Runes" || type == "String" || type == "bool" || type == "dynamic") { return false; } return true; } /// Notice: not contain all situation /// 递归获取type List getType(String type) { if (type.startsWith("List<") == false && type.startsWith("Map<") == false) { return [type]; } List results = []; if(type.startsWith("List<")) { String result = type.substring(type.indexOf("List<") + 5, type.lastIndexOf(">")); results.addAll(getType(result.trim())); } if (type.startsWith("Map<")) { List splits = type.substring(type.indexOf("Map<") + 4, type.lastIndexOf(">")).split(","); results.addAll(getType(splits[0].trim())); results.addAll(getType(splits[1].trim())); } return results; } }