Skip to content

Instantly share code, notes, and snippets.

@davidhicks980
Last active May 22, 2024 17:05
Show Gist options
  • Save davidhicks980/fb9fbfcef706e4155980a1716f87f029 to your computer and use it in GitHub Desktop.
Save davidhicks980/fb9fbfcef706e4155980a1716f87f029 to your computer and use it in GitHub Desktop.
Layered stack menu
import 'package:flutter/material.dart';
void main() => runApp(const OverlayApp());
class OverlayApp extends StatelessWidget {
const OverlayApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: OverlayExample(),
);
}
}
class OverlayExample extends StatefulWidget {
const OverlayExample({super.key});
@override
State<OverlayExample> createState() => _OverlayExampleState();
}
class _OverlayExampleState extends State<OverlayExample> {
OverlayEntry? overlayEntry;
void createHighlightOverlay(bool obstruct) {
overlayEntry = OverlayEntry(
builder: (BuildContext context) {
return SafeArea(
child: Align(
alignment: Alignment.center,
heightFactor: 1.0,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
if (obstruct)
SizedBox(
width: MediaQuery.of(context).size.width / 3,
height: 80.0,
child: Center(
child: Container(color: Color.fromRGBO(255, 0, 0, 0.5)),
),
)
else
Menu()
],
),
),
);
},
);
Overlay.of(context, debugRequiredFor: widget).insert(overlayEntry!);
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Overlay Sample'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
'Push a menu, add layers, then push an obstruction',
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () {
createHighlightOverlay(false);
},
child: const Text('Push Menu'),
),
const SizedBox(width: 20.0),
],
),
const SizedBox(height: 10.0),
ElevatedButton(
onPressed: () {
createHighlightOverlay(true);
},
child: const Text('Push Obstruction'),
),
],
),
);
}
}
class Menu extends StatefulWidget {
const Menu();
@override
State<Menu> createState() => _MenuState();
}
class _MenuState extends State<Menu> {
int layers = 1;
Color getLayerColor(int i) {
return switch (i % 3) {
0 => Colors.purple,
1 => Colors.blue,
_ => Colors.green,
};
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
for (var i = 0; i < layers; i++)
Container(
height: 100,
width: 150,
color: getLayerColor(i).withOpacity(0.95),
margin: EdgeInsets.only(top: i * 25, left: i * 25),
child: Center(child: ElevatedButton(
onPressed: () {
setState(() {
layers++;
});
},
child: Text("ADD MENU", style: TextStyle(color: Colors.black, fontSize: 10)),
)),
)
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment