generateForAnnotatedElement method
Future<String>
generateForAnnotatedElement(
- Element element,
- ConstantReader cr,
- 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
Future<String> generateForAnnotatedElement(
Element element, ConstantReader cr, BuildStep buildStep) async {
if (element is! ClassElement) return '';
final className = element.name;
final overlayName = cr.read('methodOverlayName').isNull
? element.name
: cr.read('methodOverlayName').stringValue;
final nullSafe =
cr.read('nullSafe').isNull ? true : cr.read('nullSafe').boolValue;
var fields = element.fields;
var res =
'void _\$${overlayName}FromJson($className instance, Map<String, dynamic> json) {\n'
'${fields.map((s) => 'instance.${s.displayName}=json[\'${s.displayName}\'] ${nullSafe ? 'as ${s.type.getDisplayString(withNullability: nullSafe)}' : ''};').join('\n')}'
'}\n\n\n'
'Map<String, dynamic> _\$${overlayName}ToJson($className instance) =>\n'
'<String, dynamic>{\n${fields.map((s) => '\'${s.displayName}\': instance.${s.displayName},').join('\n')}};';
return res;
}