我添加了一个 float 操作按钮和一个增加计数器变量值的增量函数,它在 float 按钮的 onressed 函数中调用。该值在控制台上发生变化,但在我的应用程序上没有变化。你能给我一个解决方案吗?
Widget build(BuildContext context) {
int counter = 0;
void incrementCounter() {
counter++;
print("You have pressed the button $counter times.");
}
return new Scaffold(
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text("You have pressed the button $counter times.")
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: incrementCounter,
child: new Icon(Icons.send),
)
);
}
第 5 行在控制台上工作,但第 13 行在我的应用程序上不工作,计数器仅为 0。我添加的代码刚好足以让您理解它。 ;)
最佳答案
每次重新渲染小部件时,您都将计数器重置为 0
,并且您不使用 setState()
更新状态,因此 Flutter 不会重新- 当值改变时渲染。
改成
int counter = 0;
void incrementCounter() {
setState(() => counter++);
print("You have pressed the button $counter times.");
}
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text("You have pressed the button $counter times.")
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: incrementCounter,
child: new Icon(Icons.send),
)
);
}
关于android - 为什么计数器变量的值在屏幕上没有变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54341050/