build method
Main build method that processes input files and generates icon font code.
This method:
- Validates the input file (must end with 'iconfont.dart')
- Reads iconfont configuration from pubspec.yaml
- Fetches SVG content from the configured URL
- Parses SVG symbols and generates Flutter widget code
- Writes the generated code to a .g.dart file
Parameters:
buildStep
: The build step context providing input/output operations
Throws:
- Exception: If there are network errors, parsing errors, or file system errors
Implementation
@override
Future<void> build(BuildStep buildStep) async {
try {
// Only process the trigger file
final inputId = buildStep.inputId;
if (!inputId.path.endsWith('iconfont.dart')) {
return;
}
// Read pubspec.yaml to get iconfont configuration
final pubspecContent = await File('pubspec.yaml').readAsString();
final pubspec = loadYaml(pubspecContent) as Map;
final iconfontConfig = pubspec['iconfont'] as Map?;
if (iconfontConfig == null) {
log.warning('No iconfont configuration found in pubspec.yaml');
return;
}
final config =
IconFontConfig.fromMap(Map<String, dynamic>.from(iconfontConfig));
if (config.symbolUrl.isEmpty ||
config.symbolUrl.contains('请参考README.md')) {
log.warning('Please configure a valid symbol_url in pubspec.yaml');
return;
}
log.info('Fetching icons from: ${config.symbolUrl}');
// Fetch SVG content
final svgContent =
await IconFontFetcher.fetchSvgContent(config.symbolUrl);
// Parse symbols
final symbols = SvgParser.parseSymbols(svgContent);
if (symbols.isEmpty) {
log.warning('No icons found in the SVG content');
return;
}
log.info('Found ${symbols.length} icons');
// Generate code content
final generatedCode = _generateIconFontCode(symbols, config);
// Write to output using BuildStep
final outputId = inputId.changeExtension('.g.dart');
await buildStep.writeAsString(outputId, generatedCode);
log.info('Successfully generated iconfont code to ${outputId.path}');
} catch (e, stackTrace) {
log.severe('Error generating iconfont: $e', e, stackTrace);
rethrow;
}
}