While using BLoC library we store all the variables in a state class. But where to store TextEditingController, which does not change, but the value of it does?
Let's say I have a state class like this (Just as example):
@freezed
abstract class EditItemState with _$EditItemState {
const factory EditItemState.updated({
TextEditingController titleController,
ShoppingItem shoppingItem,
}) = _ShoppingListLoaded;
}
And the Cubit class:
class EditItemCubit extends Cubit<EditItemState> {
EditItemCubit() : super(EditItemState.updated());
Future<void> titleUpdated() async {
emit(
EditItemState.updated().copyWith(
shoppingItem: state.shoppingItem.copyWith(
title: state.titleController.text,
),
),
);
}
}
So the Cubit class logic looks messy. I suggest to keep such controllers directly in the widget or in BLoC/Cubit class. Is it a correct approach?
Here guys asked the same question from the library authors and the answer of Felix Angelov (author of flutter_bloc) is:
I would highly recommend against maintaining TextEditingController as part of the bloc. Blocs should ideally be platform-agnostic and have no dependency on Flutter. If you need to use TextEditingControllers I would recommend creating a StatefulWidget and maintaining them as part of the State class. Then you can interface with the control in response to state changes via BlocListener
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With