【问题标题】:Flutter: Selected value doesn't display in the dropdownFlutter:所选值不显示在下拉列表中
【发布时间】:2020-01-24 05:07:05
【问题描述】:

我正在从 SQLite 数据库中填充城市名称并尝试显示为下拉列表。我按照教程使其工作,但有一个小问题。选择的值不显示在下拉列表中,它一直显示默认提示值。但是,我能够分配和检索正确的选定值。

这是我的代码:

cities.dart

class Cities {
  int id;
  String name;

  Cities(this.id, this.name);

  Cities.fromMap(Map<String, dynamic> json) {
    this.id = json["id"];
    this.name = json["name"];
  }

  Map<String, dynamic> toMap() => {
        'id': null,
        'name': name,
      };
}

Function 从 db 中检索并返回值:

Future<List<Cities>> getCitiesList() async {
Database db = await instance.database;

final citiesData = await db.query('cities');

if (citiesData.length == 0) return null;

List<Cities> citiesList = citiesData.map((item) {
  return Cities.fromMap(item);
}).toList();

return citiesList;
}

构建的代码下拉,在Widget build里面:

//these are defined above in the code
Cities _city;
final databaseHelper = DatabaseHelper.instance;

FutureBuilder<List<Cities>>(

    future: databaseHelper.getCitiesList(),
    builder: (BuildContext context, AsyncSnapshot<List<Cities>> snapshot) {
      if (!snapshot.hasData) return CircularProgressIndicator();
      return DropdownButton<Cities>(

        items: snapshot.data
            .map((city) => DropdownMenuItem<Cities>(
                  child: Text(city.name),
                  value: city,
                ))
            .toList(),
        onChanged: (Cities value) {
          setState(() {
            _city = value;
          });
        },
        isExpanded: true,
        // value: _city, //uncommenting this line breaks the layout
        hint: Text('Select City'),
      );
    },
  ),

控制台出错:

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

取消注释此 value: _city, 在显示中添加相同的错误(显示错误 8 次,而不是下拉列表)。

问题:

  1. 如何解决此问题?
  2. 如何从列表中设置默认值? (默认选中)

【问题讨论】:

  • snapshot.data 中有重复的城市吗?如果您添加value: _city,您什么时候有异常?在初始加载时还是在更改所选值之后?
  • 不,没有重复。目前,名单上只有两个城市。它发生在两个事件上,初始加载 + onChanged
  • 所以通过setting the breakpoint 在文件dropdown.dart 第620 行中调试您的应用程序,并检查断言失败的原因,我的意思是为什么items == null || items.isEmpty || value == null || items.where((DropdownMenuItem&lt;T&gt; item) =&gt; item.value == value).length == 1 不正确

标签: list flutter dart drop-down-menu sqflite


【解决方案1】:

您可以通过简单的方式做到这一点,只需创建一个简单的字符串列表并将该列表传递给下拉菜单。

方法如下:

  1. 更新您的getCitiesList() 函数:

    Future<List<String>> getCitiesList() async {
      Database db = await instance.database;
    
      final citiesData = await db.query(tblCities);
    
      if (citiesData.length == 0) return null;
    
      return citiesData.map((Map<String, dynamic> row) {
        return row["name"] as String;
      }).toList();
    }
    
  2. 在表单页面中添加:

    //initialize these at top
    List<String> _citiesList = <String>[];
    String _city;
    
    void _getCitiesList() async {
      final List<String> _list = await databaseHelper.getCitiesList();
      setState(() {
        _citiesList = _list;
      });
    }
    
  3. initState()内调用_getCitiesList();

  4. 在你的 build 方法中添加这个:

    DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          value: _city,
          items: _citiesList.map((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          }).toList(),
          onChanged: (String newValue) {
          setState(() {
              _city = newValue;
          });
          },
    )),
    

【讨论】:

  • 我想将 id 存储到我的数据库中,但我只获取字符串,所以你能帮我如何获取 id 和 name。
  • @TARUNSHARMA 我不确定,但我猜你想从数据库中检索 idname,如果是这样,那么可以通过更新 getCitiesList()return 语句来完成像这样的功能:return row["id"].toString() + row["name"] as String;。它将构建一个“ID NAME”的Map
猜你喜欢
  • 1970-01-01
  • 2021-10-26
  • 2020-01-03
  • 2012-08-12
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 2019-02-08
  • 2013-11-16
相关资源
最近更新 更多