Flutter:所选值不显示在下拉列表中

Flutter: Selected value doesn't display in the dropdown

我正在从 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:

检索和 returns 值
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. 如何从列表中设置默认值? (默认选择)

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

方法如下:

  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;
          });
          },
    )),