且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Flutter:应该只有一项具有 [DropdownButton] 的值

更新时间:2022-01-20 23:20:42

好吧,既然没有问题有完全相同的解决方案.我的代码面临同样的问题.这是我解决这个问题的方法.

Well, since no problem has an exact same solution. I was facing the same issue with my code. Here is How I fixed this.

我的下拉按钮代码:

DropdownButton(
   items: _salutations
         .map((String item) =>
             DropdownMenuItem<String>(child: Text(item), value: item))
         .toList(),
    onChanged: (String value) {
       setState(() {
         print("previous ${this._salutation}");
         print("selected $value");
         this._salutation = value;
            });
          },
     value: _salutation,
),

错误

在下面的代码片段中,我设置了一个选择值的状态,它是字符串类型.现在我的代码的问题是这个选择值的默认初始化.最初,我将变量 _salutation 初始化为:

In the code snippet below, I am setting the state for a selection value, which is of type String. Now problem with my code was the default initialization of this selection value. Initially, I was initializing the variable _salutation as:

String _salutation = ""; //Notice the empty String.

这是一个错误!

初始选择不应为 null 或为空,因为错误消息正确提及.

'items == null ||items.isEmpty ||值 == 空 ||

'items == null || items.isEmpty || value == null ||

因此崩溃:

解决方案
使用一些默认值初始化值对象.请注意值应该是您的集合中包含的值之一.如果不是,那么预计会发生崩溃.

Solution
Initialize the value object with some default value. Please note that the value should be the one of the values contained by your collection. If it is not, then expect a crash.

  String _salutation = "Mr."; //This is the selection value. It is also present in my array.
  final _salutations = ["Mr.", "Mrs.", "Master", "Mistress"];//This is the array for dropdown