Use Flutters StatefulBuilder to update state of a ModalBottomSheet

Posted by Mohammed Mahgoub on Fri, Nov 01 2019 03:00:00

You can use Flutter's StatefulBuilder to wrap your ModalBottomSheet as follows:

showModalBottomSheet(
    context: context,
    builder: (context) {
      return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState /*You can rename this!*/) {
        return Container(
          height: heightOfModalBottomSheet,
          child: RaisedButton(onPressed: () {
            setState(() {
              heightOfModalBottomSheet += 10;
            });
          }),
        );
      });
});

Please note that the new setState will override your main widget setState but sure you can just rename it so you would be able to set state of your parent widget and the modal's

showModalBottomSheet(
    context: context,
    builder: (context) {
      return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState /*You can rename this!*/) {
        return Container(
          height: heightOfModalBottomSheet,
          child: RaisedButton(onPressed: () {
            setState(() {
              heightOfModalBottomSheet += 10;
            });
          }),
        );
      });
});

This was originally posted as an answer to a question on Stackoverflow but I think it's worth sharing here also!

0 Comments

Add new comment