Android 为什么计数器变量的值在屏幕上没有变化?
我添加了一个浮动操作按钮和一个递增函数来增加计数器变量的值,这是在浮动按钮的onpressed函数中调用的。该值在控制台上更改,但在我的应用程序上不更改。你能给我一个解决办法吗Android 为什么计数器变量的值在屏幕上没有变化?,android,flutter,Android,Flutter,我添加了一个浮动操作按钮和一个递增函数来增加计数器变量的值,这是在浮动按钮的onpressed函数中调用的。该值在控制台上更改,但在我的应用程序上不更改。你能给我一个解决办法吗 Widget build(BuildContext context) { int counter = 0; void incrementCounter() { counter++; print("You have pressed the button $counter times."
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),
)
);
}
小部件构建(构建上下文){
int计数器=0;
void incrementCounter(){
计数器++;
打印(“您已按下$counter times按钮。”);
}
归还新脚手架(
正文:新中心(
子:新列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
新文本(“您已按下$counter times按钮。”)
],
),
),
floatingActionButton:新的floatingActionButton(
按下:递增计数器,
子:新图标(Icons.send),
)
);
}
第5行在控制台上工作,但第13行在我的应用程序上不工作,计数器仅为0。我已经添加了足够的代码供您理解。;) 每次重新呈现小部件时,您都将计数器重置为
0
,并且不使用setState()
更新状态,以便在值更改时颤振不会重新呈现
换成
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),
)
);
}
int计数器=0;
void incrementCounter(){
设置状态(()=>计数器++);
打印(“您已按下$counter times按钮。”);
}
小部件构建(构建上下文){
归还新脚手架(
正文:新中心(
子:新列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
新文本(“您已按下$counter times按钮。”)
],
),
),
floatingActionButton:新的floatingActionButton(
按下:递增计数器,
子:新图标(Icons.send),
)
);
}
chnage计数器++;设置状态(()=>计数器++);错误:未为类定义方法“setState”。这意味着代码位于无状态小部件中。您不能在无状态小部件中更改状态。将其更改为StatefulWidget。