如何在 Flutter 中输入值时保存 TextField 的值



我在有状态类中有此代码 变量

String sth1 ;
String sth2 ;

一旦输入了一些东西,我需要这些变量从两个文本字段中获取一个值。这就是我所拥有的

TextField(
autofocus: true,
focusNode: f1,
inputFormatters: [
LengthLimitingTextInputFormatter(1),
],
keyboardType: TextInputType.number,
onChanged: (newVal) {
if (newVal.length == 1) {
newVal = sth1;

f1.unfocus();
FocusScope.of(context).requestFocus(f2);
}

你的onChanged应该有sth1 = newVal而不是newVal = sth1

取一个

TextEditingController tec = new TextEditingController();

并将其作为控制器传递给文本字段

TextField(controller: tec);

当您想获取文本时,只需使用

tec.text;

就是这样!