readDropdownOptions function

List<String> readDropdownOptions(
  1. Element element
)

Dropdown option labels from widget items / menu entries.

Available while the menu is closed — Flutter keeps the item list on the button widget. Custom InkWell-only dropdowns have no items to read.

Implementation

List<String> readDropdownOptions(Element element) {
  final options = <String>[];
  var found = false;

  void consider(Widget widget) {
    if (found && options.isNotEmpty) return;
    if (widget is DropdownButton) {
      _collectDropdownMenuItemLabels(widget.items, options);
      found = true;
      return;
    }
    if (widget is DropdownMenu) {
      for (final entry in widget.dropdownMenuEntries) {
        final label = entry.label.trim();
        if (label.isNotEmpty) options.add(label);
      }
      found = true;
      return;
    }
    if (_isDropdownWidget(widget) &&
        widget is! DropdownButton &&
        widget is! DropdownMenu) {
      // EnsembleDropdown / DropdownButtonFormField2 / DropdownButton2 expose
      // `items` but are not part of material.dart — read dynamically.
      final items = _dynamicItemsList(widget);
      if (items != null) {
        _collectDropdownMenuItemLabels(items, options);
        found = true;
      }
    }
  }

  consider(element.widget);
  if (!found || options.isEmpty) {
    void visit(Element e) {
      if (found && options.isNotEmpty) return;
      consider(e.widget);
      e.visitChildren(visit);
    }

    element.visitChildren(visit);
  }
  if (!found || options.isEmpty) {
    element.visitAncestorElements((ancestor) {
      consider(ancestor.widget);
      return !(found && options.isNotEmpty);
    });
  }
  return List<String>.unmodifiable(options);
}