generate method
Implementation
Future<void> generate(
String featureName,
String modelName, {
List<String>? fields,
bool force = false,
bool dryRun = false,
bool withTests = true,
}) async {
if (featureName.isEmpty || modelName.isEmpty) {
throw Exception('Feature name and model name are required.');
}
if (!isSnakeCase(featureName) || !isSnakeCase(modelName)) {
throw Exception('Names must be in snake_case.');
}
final parsedFields = fields == null ? null : parseModelFields(fields);
final featureDir = getFeatureDir(featureName);
final modelsDir = p.join(featureDir, 'data', 'models');
final targetPath = p.join(modelsDir, '${modelName}_model.dart');
checkFileExists(targetPath, 'Model "$modelName"', force: force);
final testDir = p.join(
projectDir,
'test',
'features',
featureName,
'data',
'models',
);
final testPath = p.join(testDir, '${modelName}_model_test.dart');
if (dryRun) {
logDryRun('create model "$modelName"', targetPath);
if (withTests) logDryRun('create model test "$modelName"', testPath);
return;
}
ensureDirectory(modelsDir);
final className = toPascalCase(modelName);
if (parsedFields == null || parsedFields.isEmpty) {
await copyTemplate(
templateSubPath: 'model',
targetDir: modelsDir,
variables: {'model_name': modelName, 'class_name': className},
);
} else {
final imports = _collectImports(parsedFields);
await copyTemplate(
templateSubPath: 'model_with_fields',
targetDir: modelsDir,
variables: {'model_name': modelName, 'class_name': className},
lists: {
'fields': _buildFieldVariables(parsedFields),
if (imports.isNotEmpty) 'imports': imports,
},
);
}
if (withTests) {
await generateTest(
testTemplateSubPath: 'model',
testDir: testDir,
variables: {
'project_name': getProjectName(),
'feature_name': featureName,
'model_name': modelName,
'class_name': className,
},
);
}
logger.success('Model "$modelName" created in feature "$featureName".');
}