0

我想创建一个下拉按钮,当我将鼠标悬停在按钮上时它会展开。所以基本上我不必点击展开DropdownButton。有没有人有代码示例或可以帮助我?

4

1 回答 1

2

通过使用GlobalKey我们可以打开DropdownButton. 要在 Hover 上打开,我正在使用Inkwell.

结果

输出

全小部件

import 'package:flutter/material.dart';

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

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

class _StraggedExampleState extends State<StraggedExample> {
  final fromAPi = ["a", "e", "f", "a"];

  late final dropitems;
  late String initValue;

  @override
  void initState() {
    super.initState();
    final values = fromAPi.toSet().toList();
    dropitems = List.generate(
      values.length,
      (index) => DropdownMenuItem(
        child: Text("item $index"),
        value: values[index],
      ),
    );

    initValue = values[0];
  }

  GlobalKey _dropdownButtonKey = GlobalKey();

  openDropdown() {
    GestureDetector? detector;
    searchForGestureDetector(BuildContext element) {
      element.visitChildElements((element) {
        if (element.widget != null && element.widget is GestureDetector) {
          detector = element.widget as GestureDetector;
        } else {
          searchForGestureDetector(element);
        }
      });
    }

    searchForGestureDetector(_dropdownButtonKey.currentContext!);
    detector!.onTap!();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: InkWell(
          onHover: (value) {
            if (value) openDropdown();
          },
          onTap: () {},
          child: DropdownButton(
            key: _dropdownButtonKey,
            value: initValue,
            items: dropitems,
            onChanged: (value) {
              setState(() {
                initValue = value as String;
              });
            },
          ),
        ),
      ),
    );
  }
}

参考:更多细节

于 2021-08-08T02:39:31.303 回答