Home > Software engineering >  Flutter showModalBottomSheet update parent without Navigator.pop()
Flutter showModalBottomSheet update parent without Navigator.pop()

Time:01-22

In my app I would like to show a bottom sheet with showModalBottomSheet to let the user pick a font. When a new font is selected I would like to reflect the changes immediately in the parent view that is presenting the sheet without closing the sheet.

With Navigator.pop(context, value); I can easily send data back to the parent but I don't wanna close the bottom sheet on every selection.

Is there any way to achieve this behavior?

enter image description here

This it my current code to show and hide the picker modal:

In the parent view.

void showFontPicker() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        isDismissible: true,
        builder: (context) => FontPickerSheet()).then((value) {
      setState(() {
        widget.myPostcard.font = value;
      });
    });
}

In the FontPickerSheet Widget:

CupertinoPicker(
    itemExtent: 30,
    onSelectedItemChanged: (int value) {
       Navigator.pop(context, value);
    },
…

CodePudding user response:

You can pass a function to update the main state as parameter as follow:

Parent view

void showFontPicker() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        isDismissible: true,
        builder: (context) => FontPickerSheet(onSelected: updateMainView )).then((value) {
      setState(() {
        widget.myPostcard.font = value;
      });
    });
  }

  void updateMainView(value)
  {
    setState(() {
      widget.myPostcard.font = value
    });
  }

FontPickerSheet Widget

CupertinoPicker(
    itemExtent: 30,
    onSelectedItemChanged: (int value) {
       onSelected(value); // or widget.onSelected(value); [it depends on how you passed this value]
    },
…
  • Related