颤动:下拉列表中未显示所选值

时间:2019-09-24 06:17:49

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

我正在从SQLite数据库填充城市名称,并尝试显示为下拉列表。我通过遵循一个教程使它起作用,但是有一个小问题。所选值未显示在下拉菜单中,而是继续显示默认提示值。但是,我可以分配和检索正确的选定值。

这是我的代码:

from database.models import Profile, Like p=Profile(name='test', age=66) p.save() p.id AttributeError Traceback (most recent call last) <ipython-input-35-25ec00f2e4bf> in <module> ----> 1 p.id

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, }; } ,它从db检索并返回值:

Function

构建的代码在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. 的注释会在显示中添加相同的错误(显示8次错误,而不是下拉列表)。

问题:

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

1 个答案:

答案 0 :(得分: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. _getCitiesList();内致电initState()

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