gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:45:18 26 4
gpt4 key购买 nike

我正在将我的 Swift 应用程序移植到 Flutter,并且我有各种用于时间输入的文本字段,因此为了让用户只能输入有效时间,我使用 Bloc 来验证它。基本上,在每次输入时,我都会在文本字段的 onChanged 回调中使用字符串和文本字段的 TextEditingController 向 OpeningTimesBloc 发送一个 ValidateText() 事件。

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

OpeningTimesBloc 中,我进行验证并使用经过验证的字符串生成一个状态。在 OpeningTimesScreenBlocListener 中,我获取并使用新值。现在我的麻烦是,我有 28 个文本字段,因为我有早上和开放的开放和关闭时间(例如:TextEditingController monMorOp 是周一早上开放)和每个工作日下午的关闭时间。

我是否需要 28 个 TextEditingController 并对 BlocListener 中的每个 TextEditingController 进行状态检查:

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

}

或者我怎样才能只传递一个引用,它就会引导焦点所在的文本字段?也许是这样的?

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

}

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

最佳答案

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

注意:不要忘记处置所有 Controller ,否则您将收到内存泄漏警告。

关于flutter - 我必须为每个文本字段分配一个 TextEditingController 吗? flutter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61725397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com