autoCreateJsonParse function
add json method to dart source code note : if class change, should delete auto create code.
Implementation
Future<void> autoCreateJsonParse(
List<GenClassBean> genClasses, String sourcePath, bool nullSafe) async {
var fileInsertCount = <String, int>{};
genClasses
.where((value) => value.classInfo.type == ClassType.normal)
.where((element) =>
element.properties.where((element) => !element.isStatic).isNotEmpty)
.where((value) {
bool hasToJsonMethod =
value.methods.where((element) => element.name == "toJson").isEmpty;
return hasToJsonMethod;
}).forEach((classInfo) {
// print("filter result: ${classInfo.classInfo.name}");
String classPath = classInfo.path.split(":")[1];
classPath = "./lib" + classPath.substring(classPath.indexOf("/"));
if (!fileInsertCount.containsKey(classPath)) {
fileInsertCount[classPath] = 0;
}
String wantInsertLine = classInfo.path.split(":")[2];
// package:flutter_module/channel/flutter2native/account.dart:49:1
String content = _createDefaultConstructor(classInfo) + "\n";
content += _createFromJsonMethod(classInfo) + "\n";
content += _createToJsonMethod(classInfo) + "\n";
if (!nullSafe) {
content = GenFileEdit.removeDartNullSafe(content);
}
RegExp regExp = RegExp("\n");
List<String> newContentList = File(classPath).readAsLinesSync();
int newLineCount = fileInsertCount[classPath]!;
newContentList.insert(int.parse(wantInsertLine) + newLineCount, content);
String newContent = "";
newLineCount += regExp.allMatches(content).length;
newLineCount++;
fileInsertCount[classPath] = newLineCount;
newContentList.forEach((element) {
newContent += element + "\n";
});
File(classPath).writeAsStringSync(newContent);
});
for (var k in fileInsertCount.keys) {
ProcessResult result =
await Process.run('dart', ['format', k], runInShell: true);
}
}