我有一个简单的代码如下:
TextFormField(
initialValue: otp ?? "",
),
SizedBox(height: getProportionateScreenHeight(20.0)),
Text(otp ?? ""),
SizedBox(height: getProportionateScreenHeight(20.0)),
现在,我正在从一个函数调用一个api,其中api
给出了一个otp,并且需要在根本没有显示的TextFieldInput
中显示!但是它被显示在CCD_ 3中。问题出在哪里。
void processCoupon() async {
try {
if (_terms) {
print("processing mobile number !");
var data = {"mobile": _authModel.mobile};
ApiCall().postData(data, cApi).then((result) {
print(result);
if (result["data"] != null) {
print(result["data"]["otp"]);
setState(() {
otp = result["data"]["otp"].toString();
});
}
});
} else {
print("terms not agreed !");
}
} catch (e) {
print(e);
}
}
- 为
TextField
创建一个TextEditingController
:
// create a controller for the TextField
TextEditingController controller = TextEditingController();
- 将
controller
分配给您的TextField
:
TextFormField(
initialValue: otp ?? "",
// assign the controller to the TextField
controller: controller, // new line
),
SizedBox(height: getProportionateScreenHeight(20.0)),
Text(otp ?? ""),
SizedBox(height: getProportionateScreenHeight(20.0)),
- 将
otp
字符串分配给controller
的Text
属性:
void processCoupon() async {
try {
if (_terms) {
print("processing mobile number !");
var data = {"mobile": _authModel.mobile};
ApiCall().postData(data, cApi).then((result) {
print(result);
if (result["data"] != null) {
print(result["data"]["otp"]);
setState(() {
otp = result["data"]["otp"].toString();
// set the otp to be the text the controller has
controller.text = otp; // new line
});
}
});
} else {
print("terms not agreed !");
}
} catch (e) {
print(e);
}
}
我认为InitialValue只在第一个构造中使用,在您应该使用TextController更新之后。
声明:
var otpController = TextEditingController();
将控制器添加到TextFormField:
controller: otpController,
更新文本:
setState(() {
otpController.text = result["data"]["otp"].toString();
});
我知道我们可以使用TextController
实现此目的的方法,但问题是表单非常长,这是我们不能使用此方法的地方,因为需要使用对象。问题是它们inital value can be passed
,但当我们试图更新该值时,为了反映该值,我们还需要更新密钥,以便inputfield
也会更新。我刚刚添加了以下值和Voila!现在一切都很好。
TextFormField(
key: Key(otp), <--- this line was added
initialValue: otp ?? "",
),
SizedBox(height: getProportionateScreenHeight(20.0)),
Text(otp ?? ""),
SizedBox(height: getProportionateScreenHeight(20.0)),
TextFormField(
initialValue: otp ?? "",
),
变更
TextEditingController _editingController=TextEditingController();
TextFormField(initialValue: otp ?? "",controller: _editingController,);
和
setState(() {
otp = result["data"]["otp"].toString();
});
变更
setState(() {
otp = result["data"]["otp"].toString();
_editingController.text=otp;
});