skip to Main Content

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?

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)),

      ],),
    );
  }
}


3

Answers


  1. 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

    Login or Signup to reply.
  2. To fix this issue, you can move the initialization of result into the build method. This way, the result value will be updated every time the widget is rebuilt. Here’s an updated version of your _CartCounterState class:

    class _CartCounterState extends State<CartCounter> {
      late int result;
    
      @override
      void initState() {
        super.initState();
        // You can keep the initialization here if needed.
        result = widget.value;
      }
    
      @override
      Widget build(BuildContext context) {
        // Move the initialization here so that it gets updated on each rebuild.
        result = widget.value;
    
        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),
              ),
            ],
          ),
        );
      }
    }
    
    Login or Signup to reply.
  3. While both other answers work fine I would personally simply not have a separate value in your state and always work with the widget’s value. This should also fix your issue. Like

    class _CartCounterState extends State<CartCounter> {
    
    
      @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(() {
                    widget.onChange(widget.value - 1);
                  });
    
    
                }, icon: Icon(Icons.remove)),
            SizedBox(width: 60,child: Center(child: Text(widget.value.toString(),style: Theme.of(context).textTheme.headlineSmall,)),),
            IconButton(
                color: Colors.blue,
                onPressed: (){
                  setState(() {
                    widget.onChange(widget.value + 1);
                  });
                }, icon: Icon(Icons.add)),
    
          ],),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search