我是 flutter 新手,对小部件的状态没有正确的了解。我正在创建一个应用程序,在其中从主屏幕向购物车添加一些商品,然后通过单击 Cartbutton 我打开 ModalBottomSheet,用户还可以在其中修改其购物车商品,以及当用户关闭 ModalBottomSheet 而不继续操作时我想要的内容查看。它还会刷新主屏幕上选定的项目。我正在计算列表中每个项目的加法和减法。一切工作正常,唯一不工作的是主屏幕项目不会自动更新,直到我单击该项目然后它们工作正常。
基本上我想问如何在关闭 BottomModalSheet 时更新其 Parent 的状态。
这是我打开 BottomModalSheet 的 Parent 代码的一部分:
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,
),
这是 BottomModalSheet 中我设置状态的部分:
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,))
),
最佳答案
每个导航器推送方法都是异步的 - 您可以等到它弹出
showModalBottomSheet 在引擎盖下将路线推送到导航器,因此您可以在 BottomSheet 以这种方式关闭后重建您的父级
// somewhere in statefull parent
onTap:() async {
await showModalBottomSheet();
setState((){});
}
关于flutter - 如何在flutter中从ModalBottomSheet刷新ParentStatefulWidget的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62601923/