toImportStrings method

String toImportStrings(
  1. String? relativePath
)

Implementation

String toImportStrings(String? relativePath) {
  final imports = where((element) => element.imports.isNotEmpty)
      .map((e) => e.getImportStrings(relativePath))
      .where((element) => element.isNotEmpty)
      .fold<List<String>>(<String>[], (prev, current) => prev..addAll(current));

  final nestedImports = where((element) => element.nestedClasses.isNotEmpty)
      .map((e) => e.nestedClasses.map((jsonModel) => jsonModel.imports).toList())
      .fold<List<String>>(<String>[], (prev, current) => prev..addAll(current));

  imports.addAll(nestedImports);

  //remove the file that has been imported by @import
  final RegExp packageImportReg = RegExp("import 'package.*/(.+.dart)';");
  imports
      .map((e) {
        final List<RegExpMatch> matches = packageImportReg.allMatches(e).toList();
        if (matches.isEmpty) return null;
        return matches[0].group(1);
      })
      .where((element) => element != null)
      .toList()
      .forEach((element) {
        imports.removeWhere((item) => !packageImportReg.hasMatch(item) && item.contains(element!));
      });
  return imports.join('\n');
}