[英]Setstate into onpressed floatingactionbutton is not performing any changes
The following code is not updating the status of the counter.以下代码不会更新计数器的状态。 If I choose to use a function called _incremetcounter pressing the Floatingactionbutton it works.如果我选择使用名为 _incremetcounter 的 function 按下浮动操作按钮,它就可以工作。 If I place the content of the function directly into the "on pressed" action it doesn't work.如果我将 function 的内容直接放入“按下”操作中,它将不起作用。 Please explain me why?请解释一下为什么? Below also the code of the class.下面还有 class 的代码。 Regards.问候。
class _MyHomePageState extends State<MyHomePage> {
int counter = 0;
final appbarcounter = Counter(); //instance creation
void initState() {
super.initState();
appbarcounter.valuetoadd = 5;
}
void _incrementCounter() {
setState(() {
appbarcounter.incrementof();
counter = appbarcounter.countervalue;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
//onPressed: _incrementCounter,
onPressed: () {
setstate() {
appbarcounter.incrementof();
counter = appbarcounter.countervalue;
}
;
},
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class Counter {
Counter() {
this.countervalue;
this.valuetoadd;
countervalue = 0;
valuetoadd = 2;
}
int countervalue; //definisco la variabile contatore
int valuetoadd; //definisco la variabile contatore
int get number {
return valuetoadd;
}
void increment() {
countervalue++;
}
void incrementof() {
countervalue = countervalue + valuetoadd;
}
void decrement() {
countervalue--;
}
void decrementof(int valuetoadd) {
countervalue = countervalue - valuetoadd;
}
}
Change the setstate
with setState
.使用setState
更改setstate
。
use this syntax
onPressed: () {
setState(() {
appbarcounter.incrementof();
counter = appbarcounter.countervalue;
});
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.