feat: Create a mutable object starting from the state of a bloc.
- Dominant language
- Dart
- Stars
- 12.5k
- Forks
- 3.4k
- PR merge metrics
- No merged PRs in 30d
Description
**Description**
A use case I encounter in some situations (especially when creating complex forms) is having an object that changes over time but should not reside in the bloc state. For example, I have a `TextFormField` that require using a `TextEditingController` because their content can change due to actions outside the field itself. Recreating the `TextEditingController` would necessitate repositioning the cursor correctly and dealing with other issues.
A concrete example:
I have a bloc `BlocA` that manages the insertion and modification of a field `T`. In the UI, I have a `TextFormField` where I need to enter the field `T`, and with each change, a change event is triggered to `BlocA`. In addition to this field, to speed up the user experience, a QR code scanner can be used. So, values can be scanned using the camera. Upon scanning a value, a modification event is triggered to `BlocA`. Of course, the `TextFormField` must update with the new value obtained from the scan. And in any case, whether the insertion is through a QR code scan or because the user has modified a part of the content (not necessarily the end), the `TextEditingController` cursor must be positioned correctly.
**Desired Solution**
The idea is to create a widget similar to `BlocSelector`. Essentially, it involves listening to the state changes of the bloc, but in this case, to create and subsequently mutate an object (`MutableState`) looking at the previous.`MutableState` and the current bloc state. This object will then be passed as a parameter in the builder method to compose the child widget.
https://github.com/felangel/bloc/pull/4207
**Alternatives Considered**
Taking as an example the use of a TextFormField with a TextEditingController, the alternative solutions I have considered are:
- Using a `BlocSelector` to get the value from the bloc and insert it into a `TextEditingController`. However, this implies that the controller is rebuilt with every change, requiring logic to correctly reposition the cursor based on where it was previously (which I cannot determine since the selector does not have the previous state value). In the previous example, how could I determine if the value was changed through a QR code scan (where I would want the cursor at the end of the text) or if the user positioned the cursor in the middle of the text and changed a character (in which case the cursor should remain after the newly entered character)?
- Moving the controller into the bloc, but this would mean having a mutable state.
Contributor guide
Assessment
This issue has not been assessed yet.