updatePubspec method
Implementation
Future<void> updatePubspec(List<String> fontFamilies, String outputDirPath,
String pubspecPath) async {
final pubspecFile = File(pubspecPath);
// Reading the output pubspec.yaml file
final pubspecContent = await pubspecFile.readAsString();
// Parse the YAML content
final pubspecYamlCustom = loadYamlCustom(pubspecContent);
final pubspecYaml = loadYaml(pubspecYamlCustom.afterFlutter);
final newFontsSection = <Map<String, dynamic>>[];
for (var fontFamily in fontFamilies) {
// We can actually not copy the fonts, and then search the font files directly from the
// package lib/font folder using this same search
final fontFiles = Directory(outputDirPath.fixPath)
.listSync()
.whereType<File>()
.where((file) {
return path.basenameWithoutExtension(file.path).startsWith(fontFamily);
}).map((e) {
return File(e.path.replaceAll('\\', '/'));
}).toList();
final fontsList = <Map<String, dynamic>>[];
for (var fontFile in fontFiles) {
final fontWeight =
path.basenameWithoutExtension(fontFile.path).split('-').last;
final weight = _getFontWeight(fontWeight);
final assetPath =
path.join(outputDirPath, path.basename(fontFile.path)).fixPath;
final fontMap = {
'asset': assetPath,
if (weight != null) 'weight': weight,
};
fontsList.add(fontMap);
}
newFontsSection.add({
'family': fontFamily,
'fonts': fontsList,
});
}
final mutablePubspecYaml = Map<String, dynamic>.from(pubspecYaml ?? {});
final flutterSection =
Map<String, dynamic>.from(mutablePubspecYaml['flutter'] ?? {});
flutterSection['fonts'] = newFontsSection;
mutablePubspecYaml['flutter'] = flutterSection;
StringBuffer stringBuffer = StringBuffer();
final yamlWriter = YamlWriter();
var newPart = yamlWriter.write(mutablePubspecYaml);
for (var o in pubspecYamlCustom.beforeFlutter) {
stringBuffer.writeln(o);
}
stringBuffer.write(newPart);
await pubspecFile.writeAsString(stringBuffer.toString());
print(
AnsiStyles.greenBright.bold("\n✔ pubspec.yaml updated successfully."));
}