generate method
Generates Dart code for an input Dart library.
May create additional outputs through the buildStep, but the 'primary'
output is Dart code returned through the Future. If there is nothing to
generate for this library may return null, or a Future that resolves to
null or the empty string.
Implementation
@override
String generate(LibraryReader library, BuildStep buildStep) {
final annotatedWidgets = <String, String>{};
// Find all classes annotated with @NavkitRoute
for (var element in library.allElements) {
if (element is ClassElement) {
final annotation = const TypeChecker.fromRuntime(NavkitRoute).firstAnnotationOf(element);
if (annotation != null) {
String className = element.name;
final isInitialArg = annotation.getField("isInitial")?.toBoolValue();
// Determine the route name
final routeName = (isInitialArg ?? false)
? "/" // root route
: "/${className[0].toLowerCase()}${className.substring(1)}Route";
annotatedWidgets[className] = routeName;
}
}
}
// If no annotated widgets, generate nothing
if (annotatedWidgets.isEmpty) {
return "";
}
// Generate the NavkitRoutes class
final buffer = StringBuffer();
buffer.writeln("// GENERATED CODE - DO NOT MODIFY BY HAND");
buffer.writeln("// **************************************************************************");
buffer.writeln("// NavkitRoutesGenerator");
buffer.writeln("// **************************************************************************");
buffer.writeln();
buffer.writeln("class NavkitRoutes {");
buffer.writeln(" NavkitRoutes._();"); // private constructor
buffer.writeln();
// Add static constants for each route
for (var entry in annotatedWidgets.entries) {
final camelCase = _toCamelCase(entry.key);
final routeValue = entry.value;
buffer.writeln(" /// Route name for ${entry.key}");
buffer.writeln(" static const String $camelCase = '$routeValue';");
buffer.writeln();
}
// Add a map of all routes
buffer.writeln(" /// All registered routes");
buffer.writeln(" static const Map<String, String> all = {");
for (var entry in annotatedWidgets.entries) {
final routeValue = entry.value;
buffer.writeln(" \"${entry.key}\": \"$routeValue\",");
}
buffer.writeln(" };");
buffer.writeln("}");
return buffer.toString();
}