buildRoutePageFile function

String buildRoutePageFile(
  1. List<FeatureRoute> routes,
  2. String pkg
)

Builds the contents of route_page.dart from the discovered routes. A feature literally named home becomes the / route; otherwise / shows a Placeholder.

Implementation

String buildRoutePageFile(List<FeatureRoute> routes, String pkg) {
  final homeMatches = routes.where((r) => r.isHome);
  final FeatureRoute? home = homeMatches.isEmpty ? null : homeMatches.first;

  final imports = <String>[
    "import 'package:flutter/material.dart';",
    "import 'package:go_router/go_router.dart';",
    "import 'app_routes.dart';",
  ];
  for (final r in routes) {
    imports.add("import '${r.importPath}';");
  }

  final homeBuilder =
      home == null ? 'const Placeholder()' : 'const ${home.className}()';

  final entries = StringBuffer()
    ..writeln('    GoRoute(')
    ..writeln('      name: AppRoutes.home,')
    ..writeln('      path: AppRoutes.home,')
    ..writeln('      builder: (context, state) => $homeBuilder,')
    ..writeln('    ),');

  for (final r in routes) {
    if (r.isHome) continue;
    entries
      ..writeln('    GoRoute(')
      ..writeln('      name: AppRoutes.${r.routeName},')
      ..writeln('      path: AppRoutes.${r.routeName},')
      ..writeln('      builder: (context, state) => const ${r.className}(),')
      ..writeln('    ),');
  }

  return '''
// GENERATED by `river_cli generate routes`. Re-run to refresh.
${imports.join('\n')}

final GoRouter router = GoRouter(
  initialLocation: AppRoutes.home,
  routes: [
${entries.toString().trimRight()}
  ],
);
''';
}