gpt4 book ai didi

Flutter 2 - 设置自动完成 TextFormField 的初始值

转载 作者:行者123 更新时间:2023-12-03 17:09:16 24 4
gpt4 key购买 nike

我不能用 TextEditingController因为TextFormField使用 Autocomplete fieldViewBuilder TextEditingController

Autocomplete(
optionsBuilder: (TextEditingValue textEditingValue) {
if (textEditingValue.text == '') return [];

return this
.productNames
.where((Map<String, dynamic> option) {
return option['ar']
.toLowerCase()
.contains(textEditingValue.text.toLowerCase());
});
},
fieldViewBuilder: (context, textEditingController,
focusNode, onFieldSubmitted) =>
TextFormField(
controller: textEditingController,//uses fieldViewBuilder TextEditingController
focusNode: focusNode,
),
),

最佳答案

编辑
我刚刚意识到您正在使用 TextFormField,它有一个名为 initialValue 的参数。如果您不需要文本编辑 Controller ,则此答案应该有效

fieldViewBuilder: (context, textEditingController,
focusNode, onFieldSubmitted) =>
TextFormField(

focusNode: focusNode,
initialValue:"Your initial Value",
),
或者如果您使用的是 Controller ,请尝试
fieldViewBuilder: (context, textEditingController,
focusNode, onFieldSubmitted) =>
TextFormField(
controller: textEditingController..text="Initial Value",
focusNode: focusNode,
),
原答案
为什么不使用该文本编辑 Controller 本身。代码将是这样的
Autocomplete(
optionsBuilder: (TextEditingValue textEditingValue) {
if (textEditingValue.text == '') return [];

return this
.productNames
.where((Map<String, dynamic> option) {
return option['ar']
.toLowerCase()
.contains(textEditingValue.text.toLowerCase());
});
},
fieldViewBuilder: (context, textEditingController,
focusNode, onFieldSubmitted){
textEditingController.text = "Your initial text";// You can use the next snip of code if you dont want the initial text to come when you use setState((){});
return TextFormField(
controller: textEditingController,//uses fieldViewBuilder TextEditingController
focusNode: focusNode,
),
}
),
如果您正在使用 setState 并且上面的代码段不断用初始文本替换文本,请执行以下操作
Autocomplete(
optionsBuilder: (TextEditingValue textEditingValue) {
if (textEditingValue.text == '') return [];

return this
.productNames
.where((Map<String, dynamic> option) {
return option['ar']
.toLowerCase()
.contains(textEditingValue.text.toLowerCase());
});
},
fieldViewBuilder: (context, textEditingController,
focusNode, onFieldSubmitted){
textEditingController.text = textEditingController.text == ""? "Inital Text":textEditingController.text;// You can use the next snip of code if you dont want the initial text to come when you use setState((){});
return TextFormField(
controller: textEditingController,//uses fieldViewBuilder TextEditingController
focusNode: focusNode,
),
}
),
最后一个解决方案不太优雅但有效。如果我找到更好的解决方案,我会告诉你。您甚至可以将此 textEditingController 分配给在顶部声明的全局变量,并从代码中的任何位置访问它。而不是检查文本是否为空,每次 setState 时增加一个新变量的值,如果值为 == 0,则可以设置初始文本

关于Flutter 2 - 设置自动完成 TextFormField 的初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66761290/

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