projectIconFonts function

Map<String, IconFont> projectIconFonts(
  1. String root
)

The icon fonts a Flutter project at root draws with, by family: Material icons from its Flutter SDK, and CupertinoIcons when it depends on cupertino_icons. Fonts that can't be found are left out.

Packages are located through .dart_tool/package_config.json, so the project needs flutter pub get.

Implementation

Map<String, IconFont> projectIconFonts(String root) {
  final config = File(p.join(root, '.dart_tool', 'package_config.json'));
  if (!config.existsSync()) return {};
  final Map<String, String> packages;
  try {
    final json = jsonDecode(config.readAsStringSync()) as Map<String, Object?>;
    final base = config.parent.uri;
    packages = {
      for (final pkg in (json['packages'] as List).cast<Map<String, Object?>>())
        pkg['name'] as String: base
            .resolve(pkg['rootUri'] as String)
            .toFilePath(),
    };
  } on FormatException {
    return {};
  }
  final fonts = <String, IconFont>{};
  void add(String family, String? path) {
    final font = path == null ? null : IconFont.load(path);
    if (font != null) fonts[family] = font;
  }

  final flutter = packages['flutter'];
  add(
    'MaterialIcons',
    flutter == null
        ? null
        : p.join(
            flutter,
            '..',
            '..',
            'bin',
            'cache',
            'artifacts',
            'material_fonts',
            'MaterialIcons-Regular.otf',
          ),
  );
  final cupertino = packages['cupertino_icons'];
  add(
    'CupertinoIcons',
    cupertino == null
        ? null
        : p.join(cupertino, 'assets', 'CupertinoIcons.ttf'),
  );
  return fonts;
}