Flutter: Selected value doesn't display in the dropdown

最后都变了- 提交于 2019-12-23 01:15:13

问题


I'm populating cities name from SQLite database and trying to display as a drop down list. I make it work by following a tutorial, but having a small issue. The selected value is not displayed in dropdown, it keep displaying default hint value. However, I was able to assign and retrieve correct selected value.

Here is my code:

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 that retrieve and returns value from 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;
}

The code which builds drop down, inside 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'),
      );
    },
  ),

Error in the console:

'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.

Un-commenting this value: _city, add same error in display (displays error 8 times, instead of dropdown list).

Questions:

  1. How can I fix this issue?
  2. How can I set default value from the list? (which will be selected by default)

回答1:


You can do it in simple way, just create a simple list of strings and pass that list to dropdown menu.

Here's how:

  1. Update your getCitiesList() function:

    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. Add this inside your form page:

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

  4. Add this inside your build method:

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


来源:https://stackoverflow.com/questions/58074121/flutter-selected-value-doesnt-display-in-the-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!