form_bloc
form_bloc copied to clipboard
Is it possible to get the FieldBlocs that have been added to a FormBloc?
I would like to be able to iterate over the FieldBloc
s that have been added to FormBloc
. It looks like there is a private _allFieldBlocsUsed
attribute on FormBloc. Is there any way to access the FieldBloc
s 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 FieldBloc
s but, it seems like duplication!
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);