Flutter populate dropdownmenu with JSON

flutter

I am trying to take JSON returned from rest api and populate a dropdownmenu, I need to have the value different from the child value. Has anyone done this or have an example or advice. I am using the basic example and can not seem to find a way to use JSON instead of static list. Below is what I have tried and it still does not find the value. I keep getting a dart null error. Any help would be great. I have updated with how I get the JSON and decode. I have tried several things. This is the error as well, but I have confirmed in debug that the value is never null, so it has to be something with the JSON. I have tried with a static list and it works.

'package:flutter/src/material/dropdown.dart': Failed assertion: line 433 pos 15: 'value == null

String _referPractice = '<New>';

JSON looks like this:

[{"id":0,"name":"<New>"},{"id":1,"name":"Test Practice"}]


var http = createHttpClient();
var response = await http.get(_url);
var practices = await jsonCodec.decode(response.body);
practicelist = await practices.toList();

new DropdownButton<String>(
        value: _referPractice,
        isDense: true,
        onChanged: (String newValue) {
          setState(() {
            _referPractice = newValue;
          });
        },
        items: practicelist.map((value) {
          return new DropdownMenuItem<String>(
            value: value['id'].toString(),
            child: new Text(value['name']),
          );
        }).toList(),
      ),

Best Answer

You are getting this error because you are initializing _referPractice with a value that !null, and you are feeding it to the property value of the DropDownButton, which represents the currently selected item, and has to be null if no item has been selected yet.

I have replicated your example using the JSON you provided:

enter image description here

String _mySelection;
  List<Map> _myJson = [{"id":0,"name":"<New>"},{"id":1,"name":"Test Practice"}];

  @override
  Widget build(BuildContext context) {
     return new Scaffold(
        body: new Center(
          child: new DropdownButton<String>(
            isDense: true,
            hint: new Text("Select"),
            value: _mySelection,
            onChanged: (String newValue) {

              setState(() {
                _mySelection = newValue;
              });

              print (_mySelection);
            },
            items: _myJson.map((Map map) {
              return new DropdownMenuItem<String>(
                value: map["id"].toString(),
                child: new Text(
                  map["name"],
                ),
              );
            }).toList(),
          ),
        ),
      );

  }
Related Topic