如何在flutter中实现下拉列表?


79

我有一个要在Flutter中实现为下拉列表的位置列表。我是该语言的新手。这是我所做的。

new DropdownButton(
  value: _selectedLocation,
  onChanged: (String newValue) {
    setState(() {
      _selectedLocation = newValue;
     });
},
items: _locations.map((String location) {
  return new DropdownMenuItem<String>(
     child: new Text(location),
  );
}).toList(),

这是我的物品清单:

List<String> _locations = ['A', 'B', 'C', 'D'];

我收到以下错误。

Another exception was thrown: 'package:flutter/src/material/dropdown.dart': Failed assertion: line 468 pos 15: 'value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1': is not true.

我假设的值_selectedLocation将为空。但是我正在初始化它。

String _selectedLocation = 'Please choose a location';


1
问题是String _selectedLocation ='请选择一个位置'; 不在DropdownMenuItem值中。您尝试做的可能是提示。
MSquare

Answers:


129

尝试这个

new DropdownButton<String>(
  items: <String>['A', 'B', 'C', 'D'].map((String value) {
    return new DropdownMenuItem<String>(
      value: value,
      child: new Text(value),
    );
  }).toList(),
  onChanged: (_) {},
)

尝试添加value : valueDropdownMenuItem。仍然出现相同的错误。猜测value : _selectedLocationDropDownButton中的一些错误。
Chaythanya nair

1
非常感谢@Pravin Raj。您向我箭头DropdownMenuItem<String>
指示,

59

对于解决方案,滚动到答案的末尾。

首先,让我们研究错误的含义(我引用了Flutter 1.2引发的错误,但是想法是相同的):

断言失败:行560位置15:'item == null || items.isEmpty || 值== null || items.where(((DropdownMenuItem item)=> item.value == value).length == 1':不正确。

有四个or条件。必须至少满足其中之一:

  • 提供了项目(DropdownMenuItem小部件列表)。这样就消除了items == null
  • 提供了非空列表。这样就消除了items.isEmpty
  • _selectedLocation还给出了一个值()。这样就消除了value == null。请注意,这是DropdownButton的值,而不是DropdownMenuItem的值。

因此只剩下最后的检查。归结为:

遍历DropdownMenuItem。找到所有value等于的_selectedLocation。然后,检查找到了多少与之匹配的项目。必须只有一个具有此值的小部件。否则,抛出错误。

呈现代码的方式,没有DropdownMenuItem值的窗口小部件_selectedLocation。相反,所有小部件的值都设置为null。由于null != _selectedLocation,最后一个条件失败。通过设置_selectedLocationnull-验证该应用程序应运行。

要解决此问题,我们首先需要为每个设置一个值DropdownMenuItem(以便可以将某些内容传递给onChanged回调):

return DropdownMenuItem(
    child: new Text(location),
    value: location,
);

该应用程序仍将失败。这是因为您的列表仍然不包含_selectedLocation的值。您可以通过两种方式使应用程序工作:

  • 选项1。添加另一个具有值(满足items.where((DropdownMenuItem<T> item) => item.value == value).length == 1)的小部件。如果要让用户重新选择Please choose a location选项,可能会很有用。
  • 选项2。将某些内容传递给hint:paremter并设置selectedLocationnull(满足value == null条件)。如果您不想Please choose a location保留任何选择,则很有用。

请参见下面的代码,其中显示了如何执行此操作:

import 'package:flutter/material.dart';

void main() {
  runApp(Example());
}

class Example extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
//  List<String> _locations = ['Please choose a location', 'A', 'B', 'C', 'D']; // Option 1
//  String _selectedLocation = 'Please choose a location'; // Option 1
  List<String> _locations = ['A', 'B', 'C', 'D']; // Option 2
  String _selectedLocation; // Option 2

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: DropdownButton(
            hint: Text('Please choose a location'), // Not necessary for Option 1
            value: _selectedLocation,
            onChanged: (newValue) {
              setState(() {
                _selectedLocation = newValue;
              });
            },
            items: _locations.map((location) {
              return DropdownMenuItem(
                child: new Text(location),
                value: location,
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

1
谢谢。我在这个愚蠢的错误上浪费了15分钟。希望我能就您的答复提供更多的意见:)
Jawand Singh

14

您必须考虑到这一点(来自DropdownButton文档):

“项目必须具有不同的值,如果value不为null,则必须在其中。”

所以基本上你有这个字符串列表

List<String> _locations = ['A', 'B', 'C', 'D'];

并且您在Dropdown value属性中的值是这样初始化的:

String _selectedLocation = 'Please choose a location';

只需尝试以下列表:

List<String> _locations = ['Please choose a location', 'A', 'B', 'C', 'D'];

那应该工作:)

如果不想添加这样的String(不在列表上下文中),还可以检查“ hint”属性,可以使用以下内容:

DropdownButton<int>(
          items: locations.map((String val) {
                   return new DropdownMenuItem<String>(
                        value: val,
                        child: new Text(val),
                         );
                    }).toList(),
          hint: Text("Please choose a location"),
          onChanged: (newVal) {
                  _selectedLocation = newVal;
                  this.setState(() {});
                  });

8

您需要添加value: location代码才能使用它。检查这个出来。

items: _locations.map((String location) {
  return new DropdownMenuItem<String>(
     child: new Text(location),
     value: location,
  );
}).toList(),

8

使用StatefulWidgetsetState更新下拉列表。

  String _dropDownValue;

  @override
  Widget build(BuildContext context) {
    return DropdownButton(
      hint: _dropDownValue == null
          ? Text('Dropdown')
          : Text(
              _dropDownValue,
              style: TextStyle(color: Colors.blue),
            ),
      isExpanded: true,
      iconSize: 30.0,
      style: TextStyle(color: Colors.blue),
      items: ['One', 'Two', 'Three'].map(
        (val) {
          return DropdownMenuItem<String>(
            value: val,
            child: Text(val),
          );
        },
      ).toList(),
      onChanged: (val) {
        setState(
          () {
            _dropDownValue = val;
          },
        );
      },
    );
  }

下拉菜单的初始状态:

初始状态

打开下拉菜单并选择值:

选择值

将所选值反映到下拉列表中:

选择值


8

对于有兴趣实施DropDown自定义的任何人,class您都可以按照以下步骤进行。

  1. 假设您Language使用以下代码调用了一个类,并static返回了一个List<Language>

    class Language {
      final int id;
      final String name;
      final String languageCode;
    
      const Language(this.id, this.name, this.languageCode);
    
    
    }
    
     const List<Language> getLanguages = <Language>[
            Language(1, 'English', 'en'),
            Language(2, 'فارسی', 'fa'),
            Language(3, 'پشتو', 'ps'),
         ];
    
  2. 任何您想要实现的地方,DropDown您都可以importLanguage类中首先使用它,如下所示

        DropdownButton(
            underline: SizedBox(),
            icon: Icon(
                        Icons.language,
                        color: Colors.white,
                        ),
            items: getLanguages.map((Language lang) {
            return new DropdownMenuItem<String>(
                            value: lang.languageCode,
                            child: new Text(lang.name),
                          );
                        }).toList(),
    
            onChanged: (val) {
                          print(val);
                       },
          )
    

应该只有一个具有[DropdownButton]值的项目:“ Relationship”的实例。检测到零个或两个或两个以上具有相同值'package:flutter / src / material / dropdown.dart'的[DropdownMenuItem]:失败的断言:834行pos 15:'item == null || items.isEmpty || 值== null || items.where((DropdownMenuItem <T>项){返回item.value ==值;})。长度== 1'
塔伦夏尔马

重建电话后得到这个。
塔伦·夏尔马

1
亲爱的,这意味着您已经DropdownButton成功实施了。但是,程序以某种方式试图将重复的值放入Dropdown中。因此,请确保状态更改。我已经编辑了代码,并将列表列为const。请尝试一下,看看它是否可以解决您的问题。
Seddiq Sorush

7

将值放在项目中,然后它将起作用,

new DropdownButton<String>(
              items:_dropitems.map((String val){
                return DropdownMenuItem<String>(
                  value: val,
                  child: new Text(val),
                );
              }).toList(),
              hint:Text(_SelectdType),
              onChanged:(String val){
                _SelectdType= val;
                setState(() {});
                })

而且,如果您使用自定义对象(DropdownButton <MyCustomObject>),但仍然无法正常工作,只需记住为自定义对象覆盖==运算符和hashCode getter。
约尔根·安德森

5

如果您不希望它Drop list像弹出窗口一样显示。您可以像我一样以这种方式自定义它(它会显示在同一平面上,请参见下图):

在此处输入图片说明

展开后:

在此处输入图片说明

请按照以下步骤操作:首先,创建一个名为的飞镖文件drop_list_model.dart

import 'package:flutter/material.dart';

class DropListModel {
  DropListModel(this.listOptionItems);

  final List<OptionItem> listOptionItems;
}

class OptionItem {
  final String id;
  final String title;

  OptionItem({@required this.id, @required this.title});
}

接下来,创建文件file select_drop_list.dart

import 'package:flutter/material.dart';
import 'package:time_keeping/model/drop_list_model.dart';
import 'package:time_keeping/widgets/src/core_internal.dart';

class SelectDropList extends StatefulWidget {
  final OptionItem itemSelected;
  final DropListModel dropListModel;
  final Function(OptionItem optionItem) onOptionSelected;

  SelectDropList(this.itemSelected, this.dropListModel, this.onOptionSelected);

  @override
  _SelectDropListState createState() => _SelectDropListState(itemSelected, dropListModel);
}

class _SelectDropListState extends State<SelectDropList> with SingleTickerProviderStateMixin {

  OptionItem optionItemSelected;
  final DropListModel dropListModel;

  AnimationController expandController;
  Animation<double> animation;

  bool isShow = false;

  _SelectDropListState(this.optionItemSelected, this.dropListModel);

  @override
  void initState() {
    super.initState();
    expandController = AnimationController(
        vsync: this,
        duration: Duration(milliseconds: 350)
    );
    animation = CurvedAnimation(
      parent: expandController,
      curve: Curves.fastOutSlowIn,
    );
    _runExpandCheck();
  }

  void _runExpandCheck() {
    if(isShow) {
      expandController.forward();
    } else {
      expandController.reverse();
    }
  }

  @override
  void dispose() {
    expandController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            padding: const EdgeInsets.symmetric(
                horizontal: 15, vertical: 17),
            decoration: new BoxDecoration(
              borderRadius: BorderRadius.circular(20.0),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                    blurRadius: 10,
                    color: Colors.black26,
                    offset: Offset(0, 2))
              ],
            ),
            child: new Row(
              mainAxisSize: MainAxisSize.max,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Icon(Icons.card_travel, color: Color(0xFF307DF1),),
                SizedBox(width: 10,),
                Expanded(
                    child: GestureDetector(
                      onTap: () {
                        this.isShow = !this.isShow;
                        _runExpandCheck();
                        setState(() {

                        });
                      },
                      child: Text(optionItemSelected.title, style: TextStyle(
                          color: Color(0xFF307DF1),
                          fontSize: 16),),
                    )
                ),
                Align(
                  alignment: Alignment(1, 0),
                  child: Icon(
                    isShow ? Icons.arrow_drop_down : Icons.arrow_right,
                    color: Color(0xFF307DF1),
                    size: 15,
                  ),
                ),
              ],
            ),
          ),
          SizeTransition(
              axisAlignment: 1.0,
              sizeFactor: animation,
              child: Container(
                margin: const EdgeInsets.only(bottom: 10),
                  padding: const EdgeInsets.only(bottom: 10),
                  decoration: new BoxDecoration(
                    borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)),
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                          blurRadius: 4,
                          color: Colors.black26,
                          offset: Offset(0, 4))
                    ],
                  ),
                  child: _buildDropListOptions(dropListModel.listOptionItems, context)
              )
          ),
//          Divider(color: Colors.grey.shade300, height: 1,)
        ],
      ),
    );
  }

  Column _buildDropListOptions(List<OptionItem> items, BuildContext context) {
    return Column(
      children: items.map((item) => _buildSubMenu(item, context)).toList(),
    );
  }

  Widget _buildSubMenu(OptionItem item, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 26.0, top: 5, bottom: 5),
      child: GestureDetector(
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: Container(
                padding: const EdgeInsets.only(top: 20),
                decoration: BoxDecoration(
                  border: Border(top: BorderSide(color: Colors.grey[200], width: 1)),
                ),
                child: Text(item.title,
                    style: TextStyle(
                        color: Color(0xFF307DF1),
                        fontWeight: FontWeight.w400,
                        fontSize: 14),
                    maxLines: 3,
                    textAlign: TextAlign.start,
                    overflow: TextOverflow.ellipsis),
              ),
            ),
          ],
        ),
        onTap: () {
          this.optionItemSelected = item;
          isShow = false;
          expandController.reverse();
          widget.onOptionSelected(item);
        },
      ),
    );
  }

}

初始化值:

DropListModel dropListModel = DropListModel([OptionItem(id: "1", title: "Option 1"), OptionItem(id: "2", title: "Option 2")]);
OptionItem optionItemSelected = OptionItem(id: null, title: "Chọn quyền truy cập");

最后使用它:

SelectDropList(
           this.optionItemSelected, 
           this.dropListModel, 
           (optionItem){
                 optionItemSelected = optionItem;
                    setState(() {
  
                    });
               },
            )

不错的下拉菜单。谢谢
MHDEZ

4

您可以使用DropDownButtonclass来创建下拉列表:

...
...
String dropdownValue = 'One';
...
...
Widget build(BuildContext context) {
return Scaffold(
  body: Center(
    child: DropdownButton<String>(
      value: dropdownValue,
      onChanged: (String newValue) {
        setState(() {
          dropdownValue = newValue;
        });
      },
      items: <String>['One', 'Two', 'Free', 'Four']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    ),
  ),
);
...
...

请参阅此Flutter网站


3

假设我们正在创建货币下拉列表:

List _currency = ["INR", "USD", "SGD", "EUR", "PND"];
List<DropdownMenuItem<String>> _dropDownMenuCurrencyItems;
String _currentCurrency;

List<DropdownMenuItem<String>> getDropDownMenuCurrencyItems() {
  List<DropdownMenuItem<String>> items = new List();
  for (String currency in _currency) {
    items.add(
      new DropdownMenuItem(value: currency, child: new Text(currency)));
  }
  return items;
}

void changedDropDownItem(String selectedCurrency) {
  setState(() {
    _currentCurrency = selectedCurrency;
  });
}

在正文部分添加以下代码:

new Row(children: <Widget>[
  new Text("Currency: "),
  new Container(
    padding: new EdgeInsets.all(16.0),
  ),
  new DropdownButton(
    value: _currentCurrency,
    items: _dropDownMenuCurrencyItems,
    onChanged: changedDropDownItem,
  )
])

2

更改

List<String> _locations = ['A', 'B', 'C', 'D'];

List<String> _locations = [_selectedLocation, 'A', 'B', 'C', 'D'];

_selectedLocation必须是您的商品列表的一部分;


1

当我用新的动态值替换默认值时,这发生了。但是,您的代码可能以某种方式依赖于该默认值。因此,请尝试使用存储在某个备用位置的默认值来保持常量。

const defVal = 'abcd';
String dynVal = defVal;

// dropdown list whose value is dynVal that keeps changing with onchanged
// when rebuilding or setState((){})

dynVal = defVal;
// rebuilding here...

0

当我尝试在下拉列表中显示动态字符串列表时,我也遇到了DropDownButton的类似问题。我最终创建了一个插件: flutter_search_panel。不是下拉插件,但是您可以显示带有搜索功能的项目。

使用以下代码来使用小部件:

    FlutterSearchPanel(
        padding: EdgeInsets.all(10.0),
        selected: 'a',
        title: 'Demo Search Page',
        data: ['This', 'is', 'a', 'test', 'array'],
        icon: new Icon(Icons.label, color: Colors.black),
        color: Colors.white,
        textStyle: new TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0, decorationStyle: TextDecorationStyle.dotted),
        onChanged: (value) {
          print(value);
        },
   ),

0

您收到的错误是由于要求一个空对象的属性。您的商品必须为null,因此在要求比较其价值时会遇到该错误。检查您正在获取数据还是列表是对象列表而不是简单字符串。


0

当我遇到想要一个不太通用的DropdownStringButton的问题时,我刚刚创建了它:

dropdown_string_button.dart

import 'package:flutter/material.dart';
// Subclass of DropdownButton based on String only values.
// Yes, I know Flutter discourages subclassing, but this seems to be
// a reasonable exception where a commonly used specialization can be
// made more easily usable.
//
// Usage: 
// DropdownStringButton(items: ['A', 'B', 'C'], value: 'A', onChanged: (string) {})
//
class DropdownStringButton extends DropdownButton<String> {
  DropdownStringButton({
    Key key, @required List<String> items, value, hint, disabledHint,
    @required onChanged, elevation = 8, style, iconSize = 24.0, isDense = false,
    isExpanded = false, }) : 
    assert(items == null || value == null || items.where((String item) => item == value).length == 1),
        super(
          key: key,
          items: items.map((String item) {
            return DropdownMenuItem<String>(child: Text(item), value: item);
          }).toList(),
        value: value, hint: hint, disabledHint: disabledHint, onChanged: onChanged,
        elevation: elevation, style: style, iconSize: iconSize, isDense: isDense,
        isExpanded: isExpanded,
        );
    }

0

使用此代码。

class PlayerPreferences extends StatefulWidget {
  final int numPlayers;
  PlayerPreferences({this.numPlayers});

  @override
  _PlayerPreferencesState createState() => _PlayerPreferencesState();
}

class _PlayerPreferencesState extends State<PlayerPreferences> {
  int dropDownValue = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      child: DropdownButton(
        value: dropDownValue,
        onChanged: (int newVal){
          setState(() {
            dropDownValue = newVal;
          });
        },
        items: [
          DropdownMenuItem(
            value: 0,
            child: Text('Yellow'),
          ),
          DropdownMenuItem(
            value: 1,
            child: Text('Red'),
          ),
          DropdownMenuItem(
            value: 2,
            child: Text('Blue'),
          ),
          DropdownMenuItem(
            value: 3,
            child: Text('Green'),
          ),
        ],
      ),
    );
  }
}

在主体中,我们称之为

class ModeSelection extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          child: PlayerPreferences(),
        ) ,
      ),
    );
  }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.