Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

custom widget not refreshing on setState in flutter

I have created a custom widget named CartCounter But now this custom widget not refreshing on setState

On tapping reset I want to change the custom widget value to 0 but its not rebuilding..

What should i do implement to customWidget or there is another issue?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class _HomeScreen2State extends State<HomeScreen2> {
  int english = 0;
  int maths = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
            'English =' + english.toString() + ' Maths=' + maths.toString()),
      ),
      body: Column(
        children: [
          CartCounter(
              value: english,
              onChange: (value) {
                setState(() {
                  english = value;
                });
              }),
          CartCounter(
              value: maths,
              onChange: (value) {
                setState(() {
                  maths = value;
                });
              }),
          ElevatedButton(
            onPressed: () {
              setState(() {
                english = 0;
                maths = 0;
              });
            },
            child: Text('Reset'),
          ),
        ],
      ),
    );
  }
}

here is my CartCounter


class CartCounter extends StatefulWidget {
  final int value;
  final Function(int) onChange;
  const CartCounter({Key? key,required this.value,required this.onChange}) : super(key: key);

  @override
  State<CartCounter> createState() => _CartCounterState();
}

class _CartCounterState extends State<CartCounter> {
late int result;


@override
  void initState() {
    // TODO: implement initState
    super.initState();
    result=widget.value;
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,
      width: 200,
      decoration: BoxDecoration(

          borderRadius: BorderRadius.circular(20)
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
        IconButton(
            color: Colors.blue,
            onPressed: (){
              setState(() {
                result--;
                widget.onChange(result);
              });


            }, icon: Icon(Icons.remove)),
        SizedBox(width: 60,child: Center(child: Text(result.toString(),style: Theme.of(context).textTheme.headlineSmall,)),),
        IconButton(
            color: Colors.blue,
            onPressed: (){
              setState(() {
                result++;
                widget.onChange(result);
              });
            }, icon: Icon(Icons.add)),

      ],),
    );
  }
}


>Solution :

The problem is that the CartCounter widgets maintain their own internal state (result) — which is initialized in the initState method.

The thing is that initState is called only once when the widget is first created. So, even if the parent widget rebuilds and passes new value properties to CartCounter, the internal result state in CartCounter does not automatically update to reflect this new one.(even when calling setState)

So, basically, the CartCounter doesn’t know that it needs to update its result when the parent’s english or maths values change.

What you want is to force a rebuild, for that you can use Keys:

Column(
        children: [
          CartCounter(
              key: UniqueKey(), // --> add this to force the widget to rebuild
              value: english,
              onChange: (value) {
                setState(() {
                  english = value;
                });
              }),
          CartCounter(
              key: UniqueKey(), // --> add this to force the widget to rebuild
              value: maths,
              onChange: (value) {
                setState(() {
                  maths = value;
                });
              }),
          ElevatedButton(
            onPressed: () {
              setState(() {
                english = 0;
                maths = 0;
              });
            },
            child: Text('Reset Counter'),
          ),
        ],
      )

See also

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading