flutter - 您如何使用文本字段进行输入,将其放入等式中,然后在按下按钮后将输出显示为文本?
问题描述
我想在两个单独的文本字段中获取用户的输入,然后将这两个输入插入我自己的方程中。当我使用该函数时,我现在拥有的代码似乎可以工作(它打印正确的值),但是当我将它放入元素print()
时它不会更新相同的值。Text()
这是我现阶段的代码:
class PageThree extends MaterialPageRoute<Null> {
PageThree()
: super(builder: (BuildContext ctx) {
int age = 0;
int annualspend = 0;
int moneyneeded = 0;
int temp = 0;
String errormsg = '';
return Scaffold(
appBar: AppBar(
title: Text("Retirement Calculator"),
backgroundColor: Theme.of(ctx).accentColor,
elevation: 2.0,
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.all(10),
child: TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'How much money do you spend every year?',
hintStyle: TextStyle(fontSize: 16),
errorText: 'Enter an approximate estimation.',
errorStyle:
TextStyle(color: Colors.blueAccent, fontSize: 13)),
onChanged: (String str) {
setState(() {
annualspend = int.parse(str);
});
},
),
),
Container(
margin: EdgeInsets.all(10),
child: TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'By what age do you wish to retire?',
hintStyle: TextStyle(fontSize: 16),
errorText: 'Enter an integer.',
errorStyle:
TextStyle(color: Colors.blueAccent, fontSize: 13)),
onChanged: (String str) {
setState(() {
age = int.parse(str);
});
},
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Container(
margin: const EdgeInsets.all(3.0),
child: Column(
children: <Widget>[
ButtonTheme(
minWidth: 395.0,
height: 20,
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(9),
),
padding: EdgeInsets.all(12),
color: Colors.lightBlueAccent,
child: Text('Calculate',
style: TextStyle(color: Colors.white)),
onPressed: () {
setState(() {
if (age <= 85) {
moneyneeded = ((85 - age) * annualspend);
errormsg = '';
} else {
moneyneeded = 0;
errormsg =
'You entered an age greater than 85. Please enter a resonable number.';
}
});
},
),
),
Text("$temp"),
Text(errormsg)
],
)),
],
),
],
)),
);
});
}
我可能应该提到,所有的setState
事件都显示了一个错误,但它们似乎工作得很好。
在过去的两天里,我一直试图让它工作,但没有任何成功。我对颤动很陌生,所以我真的不知道该怎么做。我非常感谢您的帮助。
解决方案
问题来自将temp变量解析为Text小部件而不是moneyneeded变量。只需将其更改Text(temp)
为Text(moneyneeded)
. 并且您应该将此行添加到您的 TextField 因为输入是数字
keyboardType: TextInputType.number
推荐阅读
- javascript - SVG 文本跟踪在 iOS 设备上的呈现方式不同
- git - git pre-commit 钩子中的 git add 只添加一次文件
- bootstrap-4 - 将 Bootstrap 按钮对齐到导航栏的右侧
- python - ImportError:检测到解释器更改
- reactjs - VideoJS 没有质量级别/尽管在 Safari 桌面中具有 overrideNative,但无法选择质量
- azure - 如何使用单个 powershell 命令或脚本清理多个 Azure 资源?
- android - 连接到多个外围设备时如何通过 UUID 或其他变量分隔传入数据
- html - 使用 Rvest 进行网页抓取:登录问题
- bpmn - 当另一个分支被占用时,从并行分支停止任务
- ssis - SQL - SSIS 包在重新启动 SQL Server 代理后停止工作(密码错误)