好吧,因为没有问题有完全相同的解决方案。我的代码也面临同样的问题。这是我如何解决此问题。
我的DropdownButton的代码:
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,),错误
在下面的代码片段中,我正在设置选择类型为String的状态。现在我的代码有问题是此选择值的默认初始化。最初,我将变量初始化
_salutation为:
String _salutation = ""; //Notice the empty String.
这是一个错误!
初始选择不应为null或为空,因为正确地提到了错误消息。
‘items == null || items.isEmpty || 值== null ||
因此崩溃:
解决方案
使用一些默认值初始化值对象。 请注意 ,该 值应该是您的集合所包含的值之一。 如果不是,则可能会导致崩溃。
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


![Flutter:应该只有[DropdownButton]值的一项 Flutter:应该只有[DropdownButton]值的一项](http://www.mshxw.com/aiimages/31/399896.png)
