addRoute static method
Implementation
static Future<void> addRoute({
required String routesFilePath,
required String appRouterFilePath,
required String routeName,
required String routePath,
required String screenWidget,
required String cubit,
}) async {
try {
// 1. Update Routes file
final routesFile = File(routesFilePath);
if (!await routesFile.exists()) {
print('❌ File not found: $routesFilePath');
return;
}
String routesContent = await routesFile.readAsString();
final routesClassMatch = RegExp(
r'class\s+Routes\s*{',
).firstMatch(routesContent);
if (routesClassMatch != null) {
final insertIndex = routesContent.indexOf('}', routesClassMatch.end);
if (insertIndex != -1) {
final newConst =
' static const String $routeName = \'$routePath\';\n';
routesContent =
routesContent.substring(0, insertIndex) +
newConst +
routesContent.substring(insertIndex);
await routesFile.writeAsString(routesContent);
print('✅ The key $routeName has been added inside Routes');
}
}
// 2. Update AppRouter file
final appRouterFile = File(appRouterFilePath);
if (!await appRouterFile.exists()) {
print('❌ File not found: $appRouterFilePath');
return;
}
String routerContent = await appRouterFile.readAsString();
final routesMatch = RegExp(r'routes\s*:\s*\[').firstMatch(routerContent);
if (routesMatch != null) {
int index = routesMatch.end;
int bracketCount = 1;
while (index < routerContent.length && bracketCount > 0) {
if (routerContent[index] == '[') bracketCount++;
if (routerContent[index] == ']') bracketCount--;
index++;
}
final insertPosition = index - 1;
final newGoRoute =
'''
GoRoute(
path: Routes.$routeName,
builder: (context, state) => BlocProvider(
create: (context) => $cubit(GetIt.I.get()),
child: const $screenWidget(),
),
),''';
routerContent =
'${routerContent.substring(0, insertPosition)}\n$newGoRoute\n${routerContent.substring(insertPosition)}';
await appRouterFile.writeAsString(routerContent);
print('✅ A new GoRoute has been added inside AppRouter.routes');
}
} catch (e) {
print('❌ Error adding route: $e');
}
}