buildFacadeCommandClassRef method

String buildFacadeCommandClassRef()

Implementation

String buildFacadeCommandClassRef() {
  final hasFamily = _hasFamily;
  final hasParentAndFamily = _hasParent && hasFamily;

  String constructorParams;
  if (hasParentAndFamily) {
    constructorParams = '(this._ref, this._instance, this._familyArg)';
  } else if (_hasParent) {
    constructorParams = '(this._ref, this._instance)';
  } else if (hasFamily) {
    constructorParams = '(this._ref, this._familyArg)';
  } else {
    constructorParams = '(this._ref)';
  }

  final instanceField = _hasParent ? 'final ${parent!.name} _instance;' : '';
  final familyField = hasFamily
      ? 'final ${_familyParams.toRecordType()} _familyArg;'
      : '';

  final refField = 'final Ref _ref;';

  String commandInitialization;
  if (hasParentAndFamily) {
    commandInitialization =
        'late final _command = _instance._\$${command.name}Command(_familyArg);';
  } else if (_hasParent) {
    commandInitialization =
        'late final _command = _instance._\$${command.name}Command;';
  } else if (hasFamily) {
    commandInitialization =
        'late final _command = _\$${command.name}Command(_familyArg);';
  } else {
    commandInitialization =
        'late final _command = _\$${command.name}Command;';
  }

  // run() takes non-family params only
  // When no params, call run() without arguments but add(()) internally
  final hasNonFamilyParams = _nonFamilyParams.isNotEmpty;
  final runParams = hasNonFamilyParams
      ? _nonFamilyParams.toParameterSignature()
      : '';
  final runArgs = hasNonFamilyParams
      ? _nonFamilyParams.toRecordValue()
      : '()';

  return '''
class $facadeCommandClassNameRef {
$facadeCommandClassNameRef$constructorParams;
$instanceField
$familyField
$refField

$commandInitialization

${command.stateType} read() => _ref.read(_command);
${command.stateType} watch() => _ref.watch(_command);

SelectedRefFacade<R> select<R>(R Function(${command.stateType} state) selector) =>
    SelectedRefFacade(_ref, _command.select(selector));

void run($runParams) => _ref.read(_command.notifier).add($runArgs);
void reset() => _ref.read(_command.notifier).reset();
void retry() => _ref.read(_command.notifier).retry();
void listen(
  void Function(${command.nullableStateType} previous, ${command.stateType} next) listener, {
  void Function(Object, StackTrace)? onError,
  bool fireImmediately = false,
}) {
  _ref.listen(_command, listener, onError: onError);
}
}''';
}