Cassergio
Cassergio

Reputation: 141

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. 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;
  }
}

Upvotes: 1

Views: 866

Answers (2)

user14870151
user14870151

Reputation:

    use this syntax 
     onPressed: () {
         setState(() { 
            appbarcounter.incrementof();
            counter = appbarcounter.countervalue;
         });
     },

Upvotes: 0

Yaya
Yaya

Reputation: 4838

Change the setstate with setState.

Upvotes: 1

Related Questions