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)),
],),
);
}
}
>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