generateForAnnotatedElement method

  1. @override
String generateForAnnotatedElement(
  1. Element element,
  2. ConstantReader annotation,
  3. BuildStep buildStep
)

Implement to return source code to generate for element.

This method is invoked based on finding elements annotated with an instance of T. The annotation is provided as a ConstantReader.

Supported return values include a single String or multiple String instances within an Iterable or Stream. It is also valid to return a Future of String, Iterable, or Stream.

Implementations should return null when no content is generated. Empty or whitespace-only String instances are also ignored.

Implementation

@override
String generateForAnnotatedElement(
    Element element, ConstantReader annotation, BuildStep buildStep) {
  final className = annotation.read('className').stringValue;
  final tableName = annotation.read('tableName').stringValue;
  final columns = annotation.read('columns').listValue;
  final idFieldName = annotation.read("id").stringValue;

  List<DbColumn> columns2 = _getDefinitions(columns);
  return '''
class $className implements IOdooModel {
${_getClassTopLevelFields(columns2)}

${_getClassConstructor(className, columns2)}
factory $className.fromJson(Map<String, dynamic> json) => _\$${className}FromJson(json);
Map<String, dynamic> toJson() => _\$${className}ToJson(this);

@override
$className fromJson(Map<String, dynamic> json) {
  return $className.fromJson(json);
}

@override
int? getId() {
  return this.$idFieldName;
}

@override
String getTableName() => "$tableName";

@override
Map<String, dynamic> toJsonWithReduce(
    bool Function(MapEntry<String, dynamic> p1) validate) {
  Map<String, dynamic> fields = this.toJson();
  Map<String, dynamic> tmp = {};
  for (final field in fields.entries) {
    if (validate(field) == false) {
      continue;
    }

    tmp.putIfAbsent(field.key, () => field.value);
  }
  return tmp;
}

@override
Map<String, dynamic> toJsonWithoutNullAndId() {
  return toJsonWithReduce((MapEntry entry) {
    if (entry.value == null || entry.key == '$idFieldName') {
      return false;
    }
    return true;
  });
}

@override
List<String> getColumns() {
  List<String> resp = [];
  final tmp = this.toJson();
  for (final entry in tmp.keys) {
    resp.add(entry);
  }
  return resp;
}
}

${_getFromJson(className, columns2)}

${_getToJson(className, columns2)}
  ''';
}