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 {
final routesFile = File(routesFilePath);
if (!await routesFile.exists()) {
print('❌ File not found: $routesFilePath');
return;
}
var routesContent = await routesFile.readAsString();
final routesClassPattern = RegExp(r'class\s+Routes\s*{');
final routesClassMatch = routesClassPattern.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');
}
}
final appRouterFile = File(appRouterFilePath);
if (!await appRouterFile.exists()) {
print('❌ File not found: $appRouterFilePath');
return;
}
var routerContent = await appRouterFile.readAsString();
final routesPattern = RegExp(r'routes\s*:\s*\[');
final routesMatch = routesPattern.firstMatch(routerContent);
if (routesMatch != null) {
int startIndex = routesMatch.end;
int bracketCount = 1;
int index = startIndex;
while (index < routerContent.length && bracketCount > 0) {
if (routerContent[index] == '[') bracketCount++;
if (routerContent[index] == ']') bracketCount--;
index++;
}
int 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: $e');
}
}