簡體   English   中英

當我懸停在子菜單上時,如何讓子菜單顯示?

[英]How I can let the submenu show when I'm onHover on it?

對於 Flutter 的新版本,我正在嘗試將 TopBar 菜單與鼠標 hover 按鈕時出現的子菜單集成在一起。 但是我不能讓它在鼠標hover時顯示子菜單。

你能幫我嗎?

Flutter 3.7.0 • 通道穩定 • https://github.com/flutter/flutter.git框架 • 修訂版 b06b8b2710(3 天前) • 2023-01-23 16:55:55 -0800 引擎 • 修訂版 b24591ed3218 工具 8 • 6819608 • 6819608 2.19.0 • 開發者工具 2.20.1

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(const MenuBarApp());

class MyMenuBar extends StatefulWidget implements PreferredSizeWidget {
  const MyMenuBar({super.key});

  @override
  State<MyMenuBar> createState() => _MyMenuBarState();

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}

class _MyMenuBarState extends State<MyMenuBar> {
  final MenuController _menuController = MenuController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        MenuAnchor(
          controller: _menuController,
          style: const MenuStyle(
              backgroundColor: MaterialStatePropertyAll<Color>(Colors.black),
              padding:
                  MaterialStatePropertyAll<EdgeInsets>(EdgeInsets.all(8))),
          menuChildren: _getMenus(),
          builder: (context, controller, child) {
            return TextButton(
                child: Text("Home"),
                onPressed: () {},
                onHover: (_) {
                  if (controller.isOpen) {
                    Future.delayed(const Duration(milliseconds: 200),
                        () {
                      controller.close();
                    });
                  } else {
                    controller.open();
                  }
                });
          },
        ),
      ],
    );
  }

  List<Widget> _getMenus() {
    return [
      MenuItemButton(
        onHover: (_) {
          _menuController.open();
        },
        child: TextButton(
          onPressed: () {},
          child: const Text(
            "About",
            textAlign: TextAlign.left,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                fontSize: 16, fontWeight: FontWeight.w500, color: Colors.white),
          ),
        ),
      )
    ];
  }
}

class MenuBarApp extends StatelessWidget {
  const MenuBarApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(appBar: MyMenuBar()),
    );
  }
}

我現在能做什么

可以使用MouseRegion來實現 hover 的效果。

https://api.flutter.dev/flutter/widgets/MouseRegion-class.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM