OverlayPortal Widegt and Attributes

OverlayPortal Widegt and Attributes

The OverlayPortal widget is used to render its overlay child on an Overlay. It provides a convenient way to programmatically manage the visibility of the overlay. You can show or hide the overlay based on your application logic.

To use the OverlayPortal widget, you need to call its constructor:

Dart

OverlayPortal({
  Key? key,
  required OverlayPortalController controller,
  required Widget Function(BuildContext) overlayChildBuilder,
  Widget? child,
})
  • controller: Pass an instance of OverlayPortalController. This controller allows you to programmatically show or hide the overlay and check whether it’s currently visible.

  • overlayChildBuilder: Provide a function that returns a widget to be displayed as the overlay. You can customize this widget as needed.

  • child: Optionally, you can pass a child widget to be set as the child of the OverlayPortal’s parent.

Example Usage

Let’s create a simple example where we toggle the visibility of an overlay using a button. We’ll display the overlay with the text “This is overlay” when the button is pressed.

  1. First, create an instance of the controller:

Dart

final OverlayPortalController _overlayPortalController = OverlayPortalController();
  1. Next, create the OverlayPortal widget and pass the controller and overlay builder:

Dart

ElevatedButton(
  onPressed: () {
    _overlayPortalController.isShowing
        ? _overlayPortalController.hide()
        : _overlayPortalController.show();
  },
  child: OverlayPortal(
    controller: _overlayPortalController,
    overlayChildBuilder: (BuildContext context) {
      return const Text(
        'This is overlay',
        style: TextStyle(color: Colors.black),
      );
    },
    child: const Text('Show/Hide Overlay'),
  ),
)

In this example:

  • We create an elevated button that toggles the overlay’s visibility.

  • The overlay child displays the text “This is overlay” in black.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!