我必须为每个文本字段分配一个TextEditingController吗?扑

I'm porting my Swift app to Flutter and I have various textfields for time input so in order for user to only be able to input a valid time, I'm using Bloc to validate it. Basically at every input I send an ValidateText() event to OpeningTimesBloc with the string and textfield's TextEditingController in textfield's onChanged callback.

onChanged: (String value) {
                  print('textfield 1 onChanged: called');
                  BlocProvider.of(context)
                      .add(ValidatedText(text: value, controller: monMorOp));
                },

In OpeningTimesBloc I do the validation and yield a state with the validated string. In OpeningTimesScreen's BlocListener I get and use the new value. Now my complication is that I have 28 textfield as I have opening and closing time for morning and opening (e.g : TextEditingController monMorOp is Monday morning opening) and closing for afternoon for each weekday.

Do I need 28 TextEditingController and have a state check for each one in the BlocListener as:

if (state is ValidatedTextMonMorOp) {
            setState(() {
              monMorOp.controller.text = state.text;
            });

          }

或者我如何只传递一个参考,它将引导重点关注的文本字段?大概是这样吗?

if (state is ValidatedText) {
            setState(() {
              state.controller.text = state.text;
            });

          }

一如既往,非常感谢您的时间和帮助。

评论
  • xesse
    xesse 回复

    您必须为每个TextFormField创建一个单独的Controller,因为如果使用同一控制器,则无法区分哪个TextFormField发送哪个数据。

    注意:不要忘记处置所有控制器,否则您将收到内存舔警告。