popeyelau / wiki

📒Wiki for many useful notes, source, commands and snippets.
2 stars 0 forks source link

PopupMenuButton #35

Open popeyelau opened 3 years ago

popeyelau commented 3 years ago

2021-01-14 11 50 21

import 'package:flutter/material.dart';

class PopupMenuPage extends StatefulWidget {
  @override
  _PopupMenuPageState createState() => _PopupMenuPageState();
}

class _PopupMenuPageState extends State<PopupMenuPage> {
  static const List<String> menus = ["hello", "world"];

  bool isOpen;
  String selected;

  final GlobalKey<PopupMenuButtonState<String>> key = GlobalKey();

  @override
  void initState() {
    super.initState();
    isOpen = false;
    selected = menus.last;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black87,
      body: Center(
        child: PopupMenuButton<String>(
          key: key,
          padding: EdgeInsets.zero,
          itemBuilder: (context) => menus.map((e) {
            final color = selected == e ? Colors.orange : Colors.black;
            return PopupMenuItem(
              value: e,
              child: Container(
                width: 120,
                child: Row(
                  children: [
                    Icon(Icons.keyboard_arrow_right, color: color),
                    SizedBox(width: 6),
                    Text(e, style: TextStyle(color: color))
                  ],
                ),
              ),
            );
          }).toList(),
          child: GestureDetector(
            onTap: () {
              key.currentState.showButtonMenu();
              setState(() {
                isOpen = !isOpen;
              });
            },
            child: Container(
              decoration: BoxDecoration(
                  borderRadius: isOpen
                      ? BorderRadius.only(
                          topLeft: Radius.circular(8),
                          topRight: Radius.circular(8))
                      : BorderRadius.circular(8),
                  color: Colors.white),
              alignment: Alignment.center,
              width: 100,
              height: 40,
              child: Text("Open", style: TextStyle(color: Colors.black)),
            ),
          ),
          offset: Offset(20, 39),
          elevation: 0,
          onSelected: (e) {
            closePopup(value: e);
          },
          onCanceled: closePopup,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(8),
                  bottomLeft: Radius.circular(8),
                  bottomRight: Radius.circular(8))),
        ),
      ),
    );
  }

  closePopup({String value}) {
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        isOpen = false;
        selected = value ?? selected;
      });
    });
  }
}