Flutter BLoC library: Where to keep the TextEditingController object: in State, in BLoC / Cubit class or in the widget?

2,105

Solution 1

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

Solution 2

Personally, I have kept mine within my Cubit class. The reason for that is because I am more than likely going to be using the result of that controller at some point. To keep things clean I reference the controller's text within the Cubit rather than pass the text through an event.

Another reason is because you are able to subscribe to events, like addListener, of the controller within the Cubit, which would be considered "Business Logic".

Share:
2,105
Thomas
Author by

Thomas

Updated on November 28, 2022

Comments

  • Thomas
    Thomas over 1 year

    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?

  • Thomas
    Thomas over 3 years
    That's sounds reasonable, thanks for the answer!
  • mrgnhnt96
    mrgnhnt96 over 3 years
    You're welcome! If this answer has helped you, don't forget to accept it 😉