generateForAnnotatedElement method
Future<String>
generateForAnnotatedElement(
- Element element,
- ConstantReader annotation,
- 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 annotation, BuildStep buildStep) async {
final className = (element as ClassElement).name;
final newClassName = "_\$$className";
final fields = annotation
.read("map")
.mapValue
.entries
.map(FieldInfo.fromMapEntry)
.toList();
final strBuffer = StringBuffer();
generatePrefKeysClass(strBuffer, className, fields);
final notifierEnabled = annotation.read("changeNotifier").boolValue;
final onlyModifier = annotation.read("onlyModifier").boolValue;
final toggleMethodForBoolValues =
annotation.read("toggleMethodForBoolValues").boolValue;
final classToExtend = annotation.read("classToExtend").stringValue;
final extendsPart = classToExtend.isEmpty ? "" : "extends $classToExtend ";
strBuffer.writeln('''
class $newClassName $extendsPart${notifierEnabled ? "with ChangeNotifier" : ""} implements IEasyPrefs{
final _helper = SharedPreferencesHelper();
final _keys = const _PrefKeysFor$className();
/// if [silent] is true, value changes won't be notified.
$newClassName({bool silent = false}) {
if(silent) return;
_helper.onNotify = onValueChanged;
}
''');
if (notifierEnabled) {
strBuffer.writeln('''
@override
void onValueChanged(String key) {
notifyListeners();
}
''');
}
for (var e in fields) {
generateGettersAndSetters(
strBuffer, e, onlyModifier, toggleMethodForBoolValues);
}
strBuffer.write('''
@override
void initializeAll(){
final tmp = _helper.onNotify;
_helper.onNotify = null;
${fields.map((e) => "${e.name} = ${e.name};").join("\n")}
_helper.onNotify = tmp;
_helper.onNotify?.call("");
}
@override
bool isTouched(){
return ${fields.map((e) => "_helper.hasKey(_keys.${e.name})").join("\n || ")};
}
''');
generateToStringMethod(strBuffer, fields);
strBuffer.writeln('}');
if (annotation.read("providerExtensionMethods").boolValue) {
generateProviderExtMethods(strBuffer, className);
}
return strBuffer.toString();
}