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
The problem is that the
CartCounter
widgets maintain their own internal state (result
) — which is initialized in theinitState
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 inCartCounter
does not automatically update to reflect this new one.(even when callingsetState
)So, basically, the
CartCounter
doesn’t know that it needs to update its result when the parent’senglish
ormaths
values change.What you want is to force a rebuild, for that you can use
Keys
:See also
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:
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