Setstate into onpressed floatingactionbutton is not performing any changes
392
Change the setstate
with setState
.
Author by
Cassergio
Updated on December 27, 2022Comments
-
Cassergio over 1 year
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. If I place the content of the function directly into the "on pressed" action it doesn't work. Please explain me why? Below also the code of the 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; } }
-
Syph over 3 yearsMaybe the typo 'setstate' to 'setState'?
-
-
borchvm over 3 yearsWhile this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained.