Flutter BLoC 库:在哪里保存 TextEditingController 对象:在 State 中,在 BLoC / Cubit class 中还是在小部件中?

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

在使用 BLoC 库时,我们将所有变量存储在状态 class 中。但是TextEditingController存放在哪里,它不会改变,但是它的值却改变了?

假设我有这样的状态 class(举个例子):

@freezed
abstract class EditItemState with _$EditItemState {
  const factory EditItemState.updated({
    TextEditingController titleController,
    ShoppingItem shoppingItem,
  }) = _ShoppingListLoaded;
}

和肘 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,
        ),
      ),
    );
  }
}

所以 Cubit class 逻辑看起来很乱。我建议将此类控制器直接保留在小部件或 BLoC/Cubit class 中。这是正确的做法吗?

就我个人而言,我一直将我的腕带保持在肘 class 内。这样做的原因是因为我很可能会在某个时候使用该控制器的结果。为了保持整洁,我在 Cubit 中引用了控制器的文本,而不是通过事件传递文本。

另一个原因是因为您可以订阅 Cubit 内控制器的事件,例如 addListener,这将被视为“业务逻辑”。

Here 伙计们向图书馆作者提出了同样的问题,而 Felix Angelov(flutter_bloc 的作者)的回答是:

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