我正在尝试在用户键入时更新文本小部件,它可以工作,但我在键入时看不到输入
TextFormField(
autofocus: true,
controller: amountController,
keyboardType: TextInputType.number,
cursorColor: Colors.amber,
decoration: InputDecoration(
hintText: "Enter Amount",
prefixIcon: Material(
elevation: 0,
borderRadius: BorderRadius.all(Radius.circular(30)),
child: Icon(
Icons.phone_outlined,
size: 15,
color: Color(0xff020529),
),
),
border: InputBorder.none,
contentPadding:
EdgeInsets.symmetric(horizontal: 25, vertical: 13)),
onChanged: (value) {
add(value);
},
),
这是小部件
Text( x.toString(),
style: TextStyle(fontWeight: FontWeight.bold),
),
这是我的方法
add(String value) {
var ans = 36 * double.parse(value);
print('ddd');
setState(() {
x = ans;
});
答案 0 :(得分:0)
发生的情况是 double.parse
失败,因为给定的值无法转换为数字。
处理此问题的一种选择是使用 try catch(请参阅以下代码示例),然后将显示的值设置为 0(或者也可以执行一些操作,例如设置一条错误消息,说明“无效输入”之类的内容,如果用户输入类似内容“123d”
add(String value) {
double ans;
try {
ans = 36 * double.parse(value);
} on FormatException catch (e) {
// string couldn't be formatted to double
ans = 0;
}
setState(() {
x = ans;
});
}
我使用了 try catch,但您也可以检查 value
是否为空,和/或向 onError
添加 double.parse
回调。