Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save huynguyennovem/55f36f71f5b17b9834d5ee4e7654fba5 to your computer and use it in GitHub Desktop.
Save huynguyennovem/55f36f71f5b17b9834d5ee4e7654fba5 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
const overlaySize = 150.0;
void main() {
runApp(const MaterialApp(home: App()));
}
class App extends StatefulWidget {
const App({Key? key}) : super(key: key);
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
OverlayEntry? overlayEntry;
final GlobalKey _buttonKey = GlobalKey();
@override
void dispose() {
super.dispose();
_clearOverlay();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(
key: _buttonKey,
onPressed: () => _showOverlay(),
child: const Text('Show'),
),
),
);
}
_showOverlay() {
_clearOverlay();
overlayEntry = OverlayEntry(builder: (context) {
return GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: _clearOverlay,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final RenderBox buttonRenderBox = _buttonKey.currentContext?.findRenderObject() as RenderBox;
final buttonSize = buttonRenderBox.size;
final buttonPosition = buttonRenderBox.localToGlobal(Offset.zero);
return Stack(
children: [
Positioned(
top: buttonPosition.dy + buttonSize.height,
left: buttonPosition.dx + buttonSize.height,
child: SizedBox(
width: overlaySize,
height: overlaySize,
child: Container(
alignment: Alignment.center,
color: Colors.blue,
child: const Text(
'Hello',
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
decoration: TextDecoration.none,
),
),
),
),
)
],
);
},
),
);
});
// Add the OverlayEntry to the Overlay.
Overlay.of(context, debugRequiredFor: widget).insert(overlayEntry!);
}
_clearOverlay() {
overlayEntry?.remove();
overlayEntry = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment