A Dart package for parsing and editing Dart files, providing utilities to modify file content and manage code structure.
I often work with file generation and need to edit file content. For convenience, this package was created to help make changes to Dart files easily and quickly.
- ✨ Add content to specific classes.
- 📦 Add import statements to the top of the file.
- 🔍 Find indices of class definitions and other elements within the file.
- 🛠 Modular structure for easier maintenance and readability.
Add dart_file_editor
to your pubspec.yaml
:
dependencies:
dart_file_editor: ^0.0.1
Then run flutter pub get to install the package.
Use DartFileEditor.addContentToClass to add content to a specific class in a Dart file:
import 'package:dart_file_editor/dart_file_editor.dart';
void main() {
String content = '''
class MyClass {
// existing content
}
''';
String updatedContent = DartFileEditor.addContentToClass(
content,
className: 'MyClass',
contentToAdd: 'int newField;',
);
print(updatedContent);
}
Use DartFileEditor.addImports to add import statements at the top of a Dart file:
import 'package:dart_file_editor/dart_file_editor.dart';
void main() {
String content = '''
import 'package:existing/package.dart';
void main() {
// code
}
''';
String updatedContent = DartFileEditor.addImports(
content,
imports: [
"import 'package:new/package1.dart';",
"import 'package:new/package2.dart';",
],
);
print(updatedContent);
}
Use IndexHelpers to find various indices in the Dart file content:
import 'package:dart_file_editor/dart_file_editor.dart';
void main() {
String content = '''
class MyClass {
// existing content
}
class AnotherClass {
// other content
}
''';
int classStartIndex = IndexHelpers.findClassStartIndex('MyClass', content);
print('Class start index: $classStartIndex');
int classEndIndex = IndexHelpers.findClassEndIndex('MyClass', content);
print('Class end index: $classEndIndex');
}
Method | Description |
---|---|
addContentToClass | Adds the specified content to the specified class in the file content. |
addImports | Adds the specified import statements to the top of the file content. |
Method | Description |
---|---|
findClassStartIndex | Finds the starting index of the specified class in the file content. |
findClassEndIndex | Finds the ending index of the specified class in the file content. |
findLastIndexContaining | Finds the last index of a line that contains the specified element (substring). |
findLastIndexMatching | Finds the last index of a line that exactly matches the specified element. |
findLastIndexStartsWith | Finds the last index of a line that starts with the specified element. |
Contributions are welcome! Please open an issue or submit a pull request on GitHub.
This project is licensed under the MIT License - see the LICENSE file for details.