crudControllerTemplate function

String crudControllerTemplate(
  1. String name,
  2. ProjectContext ctx
)

An AsyncNotifier-based CRUD controller that delegates to the repository.

Implementation

String crudControllerTemplate(String name, ProjectContext ctx) {
  final className = '${Naming.pascal(name)}Controller';
  final modelName = Naming.pascal(name);
  final repoName = '${Naming.pascal(name)}Repository';
  final pkg = ctx.packageName ?? 'app';
  final snake = Naming.snake(name);

  return '''
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:$pkg/data/models/${snake}_model.dart';
import 'package:$pkg/data/repositories/${snake}_repository.dart';

/// Loads and mutates the list of $modelName items. All business logic lives
/// here; the view stays declarative and reads state via `ref.watch`.
class $className extends AsyncNotifier<List<$modelName>> {
  final $repoName _repository = $repoName();

  @override
  Future<List<$modelName>> build() => _repository.fetchAll();

  /// Re-fetches the list, surfacing errors through [AsyncValue].
  Future<void> refresh() async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(_repository.fetchAll);
  }

  Future<void> add($modelName item) async {
    await _repository.create(item);
    await refresh();
  }

  Future<void> update(String id, $modelName item) async {
    await _repository.update(id, item);
    await refresh();
  }

  Future<void> remove(String id) async {
    await _repository.delete(id);
    await refresh();
  }
}
''';
}