如何在 Flutter 的 DropdownButton 中使用 TextEditingController?

How to use TextEditingController in DropdownButton in Flutter?

我无法同时使用 DropdownButton 和 TextEditingController。我正在尝试在带有文本条目的屏幕中获取用户表单数据,解析我收到的数据并通过 API 调用 http.post 发送它。由于应用程序结构,我不得不使用控制器。

我应该如何定义变量?或者我应该如何设置 DropdownButton 字段?

我收到此错误消息:“应该只有一项带有 [DropdownButton]'s value'。 这是完整的错误;

Exception has occurred.
_AssertionError ('package:flutter/src/material/dropdown.dart': Failed assertion: line 839 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1': There should be exactly one item with [DropdownButton]'s value: TextEditingController#82061(TextEditingValue(text: ┤├, selection: TextSelection(baseOffset: -1, extentOffset: -1, affinity: TextAffinity.downstream, isDirectional: false), composing: TextRange(start: -1, end: -1))). 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value)

这里我在控制器中定义变量;

class _TransferDataWidget extends State {
  // Getting value from TextField widget.
  TextEditingController shift= TextEditingController();
}

为了调用 API,我从 Controller 获取值并进行解析;

// Getting value from Controller
String shift1 = shift.text;

这是表单输入字段;

//String shift DropdownButton
Container(
width: 280,
padding: EdgeInsets.all(10.0),
margin: EdgeInsets.fromLTRB(0, 0, 0, 10),
child: Column(
  children: <Widget>[
    Text('Shift : ?'),

    Row(
      children: [
        Flexible(
          fit: FlexFit.loose,
          child:
          DropdownButton(
            value: shift,
            items: [
              DropdownMenuItem(child: Text("Gece"), value: 'gece',),
              DropdownMenuItem(child: Text("Gunduz"), value: 'gunduz',),
            ],
            onChanged: ( value) {
              setState(() {
                shift = value;
              });
            },

          ),

        ),
      ],
    ),


  ],
) ,
),

下拉按钮没有控制器 属性 你可以查看文档 https://api.flutter.dev/flutter/material/DropdownButton-class.html If you want to use text editing controller, you can use this package dropdown_search https://pub.dev/packages/dropdown_search 它有 searchBoxController 属性 用于 TextEditingController