How to Update State of Parent StatefulWidget from other Child StatefulWidget in Flutter?
Hi! all today we going to learn how we can update or change text of parent StatefulWidget in appbar from the child StatefulWidget in flutter.
Same as we can also change any color, icon or other data of parent widget.
class ParentWidget extends StatelessWidget {int cartitem = 0;@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(titleSpacing: 0,leading: Icon(Icons.location_on,size: 20,color: Colors.white,),title: Text("Title"),actions: <Widget>[Stack(children: [IconButton(icon: Icon(Icons.shopping_cart),color: Colors.white,),Positioned.directional(textDirection: Directionality.of(context),top: 8,end: 12,child: CircleAvatar(backgroundColor: Colors.red,radius: 5.5,child: Center(child: Text(cartitem.toString(),style: Theme.of(context).textTheme.bodyText2!.copyWith(color: Theme.of(context).scaffoldBackgroundColor,fontSize: 9),)),),)],),],),body: ChildWidget(function: refreshCart));}refreshCart() {setState(() {cartitem++;print("cart item updated : " + cartitem.toString());});}}class ChildWidget extends StatefulWidget {final VoidCallback function;ChildWidget({Key? key, required this.function}) : super(key: key);@overrideChildWidgetState createState() => ChildWidgetState();}class ChildWidgetState extends State<ChildWidget> {@overrideWidget build(BuildContext context) {return Container(color: Colors.teal,width: double.infinity,alignment: Alignment.center,child: ElevatedButton(child: Text("Call method in parent"),onPressed: () => widget.function(), // calls method in parent),);}}
Given code will update count of cart in parent widget from child widget on button click.
Output :
The above written code is working fine hope this work for you also in your concept.
Thankyou for visiting here.

Comments
Post a Comment