addImport method
Add an import statement to a Dart file The import will be added after the last existing import
Implementation
Future<void> addImport(String filePath, String importStatement) async {
if (!fileExists(filePath)) {
error('File not found: $filePath');
return;
}
String content = await readFile(filePath);
// Check if import already exists
if (content.contains(importStatement)) {
comment('Import already exists in $filePath');
return;
}
// Find the last import statement
final importRegex = RegExp(r"^import .*?;$", multiLine: true);
final matches = importRegex.allMatches(content).toList();
if (matches.isNotEmpty) {
final lastImportEnd = matches.last.end;
content = content.substring(0, lastImportEnd) +
'\n$importStatement' +
content.substring(lastImportEnd);
} else {
// No imports found, add at the beginning
content = '$importStatement\n$content';
}
await writeFile(filePath, content);
}