问题
I'm new to flutter and I don't have proper idea about the states of a widget. I'm creating an application where I'm adding some items to the cart from home screen and by clicking on Cartbutton I'm opening ModalBottomSheet where user can also modify their cart items, and what I want when user close the ModalBottomSheet without proceeding for checkout. it refreshes the selected items at home screen as well. I'm calculating addition and subtraction of each item into a list. Everything is working fine, the only thing which is not working is home screen items did not updates automatically untill I click on to that item and then they works fine.
Basically I want to ask how to update states of Parent of BottomModalSheet on closing it.
Here is a part of code of Parent where I'm opening BottomModalSheet:
child: Material(
color: Colors.transparent,
child: InkWell(
splashColor: Colors.black12,
onTap: () async{
await scaffoldKey.currentState
.showBottomSheet((context) =>
StatefulBuilder(
builder: (BuildContext context,StateSetter setState){
return Container(
color: Colors.white,
height: MediaQuery.of(context).size.height,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
height: 200,
color: Colors.black,
),
And This is the part of BottomModalSheet where I'm Setting the state:
InkWell(
onTap: (){
totalItems.remove(1);
totalPrice.remove(int.parse(categoryItemList[index].OurPrice));
cart.remove(categoryItemList[index]);
setState(() {<----------------------------------------Here I'm calling setState()
if(categoryItemList[index].Counter<2)
{
categoryItemList[index].ShouldVisible = !categoryItemList[index].ShouldVisible;
if(totalItems.length<1)
{
showCart = !showCart;
}
}else{
categoryItemList[index].Counter--;
}
});
print(categoryItemList[index].Counter);
// print(searchedItemList[index].Counter);
}
,child: Container(
height: 30,
child: Icon(Icons.remove,color: Colors.green,size: 18,))
),
回答1:
Every Navigator push metod is async - you can wait till it poped
showModalBottomSheet under the hood pushes route to navigator, so you can rebuild your parent after bottomSheet closed this way
// somewhere in statefull parent
onTap:() async {
await showModalBottomSheet();
setState((){});
}
来源:https://stackoverflow.com/questions/62601923/how-to-refresh-the-states-of-parentstatefulwidget-from-modalbottomsheet-in-flutt