Warwick
Warwick

Reputation: 1240

How to prevent Overlay from covering AppBar?

I have a custom widget positioned in a Stack. This custom widget creates an OverlayEntry linked to its position and inserts it into an Overlay.

The problem is that this overlay floats above the AppBar and the FloatingActionButton.

How to put OverlayEntry below the AppBar but above the contents of my Stack?

UPD: By "below" I mean that the AppBar should float over the OverlayEntry (or cover it, as if it has a bigger z-index).

This is what I have:

enter image description here

This is what I'd like to have:

enter image description here

Sample code:

import 'package:flutter/material.dart';

main() {
  runApp(
    MaterialApp(
      home: OverlayDemo(),
    ),
  );
}

class OverlayDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AppBar + Overlay'),
      ),
      body: Stack(
        children: [
          Positioned(
            top: 10,
            left: 100,
            child: WidgetWithOverlay()
          )
        ],
      )
    );
  }
}


class WidgetWithOverlay extends StatefulWidget {
  const WidgetWithOverlay({
    Key? key,
  }) : super(key: key);

  @override
  _WidgetWithOverlayState createState() => _WidgetWithOverlayState();
}

class _WidgetWithOverlayState extends State<WidgetWithOverlay> {
  OverlayEntry? overlayEntry;

  void showOverlay() {
    print(overlayEntry);
    if (overlayEntry == null) {
      overlayEntry = OverlayEntry(
          builder: (BuildContext context) {
            return Positioned(
                top: 0.0,
                left: 0.0,
                child: IgnorePointer(
                  child: Container(
                    width: 100,
                    height: 100,
                    color: Colors.green,
                  ),
                )
            );
          }
      );
      Overlay.of(context)!.insert(overlayEntry!);
    }
  }

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: showOverlay,
      child: Text('Show Overlay')
    );
  }
}

Upvotes: 5

Views: 2315

Answers (3)

dainiusm07
dainiusm07

Reputation: 126

You could try wrapping your Scaffold body with Overlay.wrap

Upvotes: 0

Rai Rizwan
Rai Rizwan

Reputation: 21

put Stack above the scaffold then first child of stack will be WidgetWithOverlay() second child scaffold.

Upvotes: 0

stacker
stacker

Reputation: 4485

by default the Appbar height is kToolbarHeight,so you can create your overlay like so:

  overlayEntry = OverlayEntry(
      builder: (BuildContext context) {
        return Positioned(
            top: kToolbarHeight,
            left: 0.0,
            child: IgnorePointer(
              child: Container(
                width: 100,
                height: 100,
                color: Colors.green,
              ),
            )
        );
      }
  );

Upvotes: -1

Related Questions