addFont method
Adds a font configuration under the flutter: fonts: section.
Implementation
void addFont(String pubspecPath, String fontFamily, List<String> fontPaths) {
final file = File(pubspecPath);
if (!file.existsSync()) {
throw CliException('pubspec.yaml not found at $pubspecPath');
}
final lines = file.readAsLinesSync();
int flutterIndex = -1;
for (int i = 0; i < lines.length; i++) {
if (lines[i].trim() == 'flutter:' && !lines[i].startsWith(' ')) {
flutterIndex = i;
break;
}
}
if (flutterIndex == -1) {
lines.add('');
lines.add('flutter:');
lines.add(' fonts:');
lines.add(' - family: $fontFamily');
lines.add(' fonts:');
for (final path in fontPaths) {
lines.add(' - asset: $path');
}
file.writeAsStringSync(lines.join('\n'));
return;
}
int fontsIndex = -1;
for (int i = flutterIndex + 1; i < lines.length; i++) {
final line = lines[i];
if (line.isNotEmpty && !line.startsWith(' ') && !line.startsWith('#')) {
break; // Out of flutter section
}
if (line.trim() == 'fonts:') {
fontsIndex = i;
break;
}
}
final fontConfig = <String>[];
fontConfig.add(' - family: $fontFamily');
fontConfig.add(' fonts:');
for (final path in fontPaths) {
fontConfig.add(' - asset: $path');
}
if (fontsIndex == -1) {
// Insert ' fonts:' and configuration
lines.insertAll(flutterIndex + 1, [' fonts:', ...fontConfig]);
} else {
// Insert configuration under ' fonts:'
lines.insertAll(fontsIndex + 1, fontConfig);
}
file.writeAsStringSync(lines.join('\n'));
}