Flutter:应该只有[DropdownButton]值的一项 [英] Flutter: There should be exactly one item with [DropdownButton]'s value

查看:538
本文介绍了Flutter:应该只有[DropdownButton]值的一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Flutter中创建一个下拉按钮。我从数据库中获取了一个列表,然后将该列表传递给了我的 dropdownButton 一切正常,数据显示为意图,但当我从中选择一个元素时,出现此错误:

 应该只有一个带有[DropdownButton的项目]的值:标签的实例。 
检测到零个或两个或两个以上具有相同值的[DropdownMenuItem]
'package:flutter / src / material / dropdown.dart':
失败的断言:805行pos 15: 'items == null || items.isEmpty ||值== null ||
items.where(((DropdownMenuItem< T> item){
return item.value == value;
})。length == 1'

我尝试将 DropdownButton值设置为null ,但是可以,但是我看不到所选元素。 / p>

这是我的代码:

  FutureBuilder< List< Tag>>(
未来: _tagDatabaseHelper.getTagList(),
builder:(BuildContext context,AsyncSnapshot< List< Tag>>快照){
if(!snapshot.hasData){
return Center(
子级:CircleProgressIndicator(),
);
}
返回ListView(
子级:< Widget> [
SizedBox(
高度:MediaQuery.of (context).size.height * 0.2,
),
Container(
保证金:EdgeInsets.symmetric(
水平:MediaQuery.of(context).size.width * 0.07 ),
子代:Theme(
数据:ThemeData(canvasColor:Color(0xFF525A71)),
子代:DropdownButton< Tag>(
值:_selectedTag,
isExpanded:true,
图标:Icon(
Icons.arrow_drop_down,
大小:24,
),
提示:文本(
选择标签,
样式:TextStyle(color:Color(0xFF9F9F9F)),
),
onChanged:(value){
setState((){
_selectedTag = value;
});
},
项:snapshot.data.map((Tag tag){
return DropdownMenuItem< Tag>(
value:tag,
child:Text(
tag.tagTitle,
样式:TextStyle(color:Colors.white),
),
);
})。toList(),
值:_selectedTag,
),
),
),

我使用了 futureBuilder 即可从数据库中获取我的列表

解决方案

好吧,因为没有问题有完全相同的解决方案。我的代码也面临同样的问题。这是我的解决方法。



DropdownButton的代码:

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

错误



在代码中在下面的代码段中,我正在为选择类型(字符串类型)设置状态。现在我的代码有问题是此选择值的默认初始化。
最初,我将变量 _salutation 初始化为:

  String _salutation =; //注意空字符串。 

这是一个错误!



初始选择不应为null或为空,因为正确提到了错误消息。


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


因此崩溃:



< a href = https://i.stack.imgur.com/8ny32.png rel = noreferrer>



解决方案
使用某些默认值初始化值对象。 请注意值应该是集合中包含的值之一。如果不是,则可能会导致崩溃。

 字符串_salutation = Mr.; //这是选择值。它也存在于我的数组中。 
final _salutations = [ Mr., Mrs., Master, Mistress]; //这是下拉菜单


I am trying to create a dropdown button in Flutter. I am getting a List from my database then I pass the list to my dropdownButton everything works the data is shown as intended but when I choose an element from it I get this error:

There should be exactly one item with [DropdownButton]'s value: Instance of 'Tag'. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 805 pos 15: 'items == null || items.isEmpty || value == null ||
          items.where((DropdownMenuItem<T> item) {
            return item.value == value;
          }).length == 1'

I tried setting DropdownButton value to null it works but then I can't see the chosen element.

Here is my code:

FutureBuilder<List<Tag>>(
    future: _tagDatabaseHelper.getTagList(),
    builder: (BuildContext context, AsyncSnapshot<List<Tag>> snapshot) {
      if (!snapshot.hasData) {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
      return ListView(
        children: <Widget>[
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.2,
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: MediaQuery.of(context).size.width * 0.07),
            child: Theme(
              data: ThemeData(canvasColor: Color(0xFF525A71)),
              child: DropdownButton<Tag>(
                value: _selectedTag,
                isExpanded: true,
                icon: Icon(
                  Icons.arrow_drop_down,
                  size: 24,
                ),
                hint: Text(
                  "Select tags",
                  style: TextStyle(color: Color(0xFF9F9F9F)),
                ),
                onChanged: (value) {
                  setState(() {
                    _selectedTag = value;
                  });
                },
                items: snapshot.data.map((Tag tag) {
                  return DropdownMenuItem<Tag>(
                    value: tag,
                    child: Text(
                      tag.tagTitle,
                      style: TextStyle(color: Colors.white),
                    ),
                  );
                }).toList(),
                value: _selectedTag,
              ),
            ),
          ),

I used futureBuilder to get my List from database.

解决方案

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

CODE of my 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,
),

The Error

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.

This was a mistake!

Initial selection should not be null or empty as the error message correctly mentioned.

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

And hence the crash:

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

这篇关于Flutter:应该只有[DropdownButton]值的一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆