form_bloc icon indicating copy to clipboard operation
form_bloc copied to clipboard

Is it possible to get the FieldBlocs that have been added to a FormBloc?

Open maxpeterson opened this issue 4 years ago • 1 comments

I would like to be able to iterate over the FieldBlocs that have been added to FormBloc. It looks like there is a private _allFieldBlocsUsed attribute on FormBloc. Is there any way to access the FieldBlocs in a subclass?

I would like to create a generic FormBloc that performs generic operations on the fields. As an example, here is a simplified version of of my LoginFormBloc passing the errors from my API to the field block using allFieldBlocsUsed.

class LoginFormBloc extends FormBloc<String, String> {
  UserRepository _userRepository;
  final email = TextFieldBloc(name: 'email');

  final password = TextFieldBloc(name: 'password');

  LoginFormBloc({
    @required UserRepository userRepository,
  })  : assert(userRepository != null),
        _userRepository = userRepository,
        super() {
    addFieldBlocs(
      fieldBlocs: [email, password],
    );
  }

  @override
  void onSubmitting() async {
    final failureResponse = 'Failed to sign in';
    try {
      await _userRepository.signIn(email.value, password.value);
      emitSuccess();
    } on APIErrors catch (errors) {
      allFieldBlocsUsed.forEach((fieldBloc) {
        final String name = fieldBloc.state.name;
        if (errors.hasErrors(name)) {
          fieldBloc.addFieldError(errors.fieldError(name).message);
        }
      });
      emitFailure(failureResponse: failureResponse);
    } catch (_) {
      emitFailure(failureResponse: failureResponse);
    }
  }
}

I could keep track of the list of FieldBlocs but, it seems like duplication!

maxpeterson avatar Jul 31 '20 08:07 maxpeterson

Hello, I will consider it.

I want to redesign the field blocs and the form bloc to make it more extensible, but I have not had time since it is a big change, but I think I will save time the next week.

I will review the issues in a few days in case you want to give suggestion or request for features.

At the moment you can use this, but as it is an internal use in future versions it may disappear.

import 'package:form_bloc/src/blocs/field/field_bloc.dart';

      final allSingleFieldBlocs =
          FormBlocUtils.getAllSingleFieldBlocs(state.fieldBlocs().values);

GiancarloCode avatar Aug 02 '20 05:08 GiancarloCode