本文介绍了如何在 Flutter 中更新 ModalBottomSheet 的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码很简单:显示一个模态的底部表单,当用户点击按钮时,表单的高度增加了 10.

This code is very simple: shows a modal bottom sheet and when the uses clicks the button, it increases the height of the sheet by 10.

但是什么也没发生.实际上,只有当用户用手指滑动"底部工作表时,它才会更新其大小(我相信滑动会导致工作表上的内部 setState).

But nothing happens. Actually, it only updates its size if the user "slides" the bottom sheet with it's finger (I belive that swipe causes a internal setState on the sheet).

我的问题是:如何调用 ModalBottomSheet 的更新状态?

My question is: how do I call the update state of a ModalBottomSheet?

showModalBottomSheet(
    context: context,
    builder: (context) {
      return Container(
        height: heightOfModalBottomSheet,
        child: RaisedButton(

            onPressed: () {
              setState(() {
                heightOfModalBottomSheet += 10;
              });

            }),
      );
    });

推荐答案

您也许可以使用 ScaffoldState 中的 showBottomSheet.在此处了解有关此 showBottomSheet 的更多信息.

You can maybe use the showBottomSheet from the ScaffoldState. read more here about this showBottomSheet.

这将显示bottomSheet并返回一个控制器PersistentBottomSheetController.使用此控制器,您可以调用 controller.SetState((){}) 来重新渲染 bottomSheet.

This will show the bottomSheet and return a controller PersistentBottomSheetController. with this controller you can call controller.SetState((){}) which will re-render the bottomSheet.

这是一个例子

PersistentBottomSheetController _controller; // <------ Instance variable
final _scaffoldKey = GlobalKey<ScaffoldState>(); // <---- Another instance variable
.
.
.
void _incrementBottomSheet(){
    _controller.setState(
        (){
            heightOfModalBottomSheet += 10;
        }
    )
}
.
void _createBottomSheet() async{
  _controller = await _scaffoldKey.currentState.showBottomSheet(
        context: context,
        builder: (context) {
           return Container(
               height: heightOfModalBottomSheet,
               child: RaisedButton(
               onPressed: () {
                  _incrementBottomSheet()
              }),
         );
      });
}

这篇关于如何在 Flutter 中更新 ModalBottomSheet 的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 16:46