Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The function setState is not defined. Flutter

I'm trying to change the colour of my checkbox(actually custom checkbox) for this I have written the code below , while I press the icon the onPressed() method is called but the colour of the icon doesn't change at all.

My widgets setState() is un-recognized. I have included import package:flutter/material.dart

here's the code

Widget _choice() {
var isPressed = false;
return Container(
height: 90,
width: 160,
color: Color(0xFFe6e9ed),
child: Column(
  children: <Widget>[
    Align(
      alignment: Alignment(0.9, 0),
      child: IconButton(
        icon: Icon(
          Icons.check_circle,
          size: 25,
            color:(isPressed) ? Color(0xff007397) : Color(0xff9A9A9A)
        ),
      onPressed: (){
        setState((){ // <--  this setState is un-recognizable by flutter ide
          if(isPressed){ print("checkbox pressed");
          isPressed = false;
          } else {
            isPressed = true;
          }
        });
      },
      ),
    ),
    Align(
      alignment: Alignment(-0.8, 0),
      child: Text("Category choice 1"),
    ),
    Align(
      alignment: Alignment(0.9, 0),
      child: Icon(
        Icons.phonelink,
        size: 40,
      ),
    ),
  ],
),);}
like image 284
Shafqat Nadeem Avatar asked Oct 14 '25 12:10

Shafqat Nadeem


1 Answers

You must use a StatefulWidget.

A widget that has mutable state.

State is information that (1) can be read synchronously when the widget is built and (2) might change during the lifetime of the widget. It is the responsibility of the widget implementer to ensure that the State is promptly notified when such state changes, using State.setState. For example

class MyDemo extends StatefulWidget {
  @override
  _MyDemoState createState() => _MyDemoState();
}

class _MyDemoState extends State<MyDemo> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: IconButton(icon: null, onPressed: (){
        setState(() {
          //Do your stuff
        });
      }),
    );
  }
// every method which changes state should exist within class only
  Widget _check(){
    return IconButton(icon: null, onPressed: (){
      setState(() {

      });
    });
  }

}
like image 164
Ravinder Kumar Avatar answered Oct 17 '25 01:10

Ravinder Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!