type 'List<dynamic>' is not a subtype of type 'List<DropdownMenuItem<String>>'

danu picture danu · Jun 25, 2019 · Viewed 9.4k times · Source

Im working on a flutter project where i pass an array of objects (List> array) to the stream-builder from my bloc. If i print the object it prints nicely, but when i try to map them out in the DropdownMenuItem, it throws me the mentioned error. Hence, if i create a dummy array in the same format within the class and access it i do not get the error. not sure what am I missing here, code as bellow.

          StreamBuilder(
          stream: _bLoc.getJsonArray,
          builder: (context, snapshot) {
            return snapshot.hasData
                ? new Container(
                    width: 150,
                    color: Theme.of(context).primaryColor,
                    child: new DropdownButton<String>(
                      items: snapshot.data.map((value) =>
                         new DropdownMenuItem<String>(
                          value: value["distance"],
                          child: new Text(value["distance"]),
                        )
                      ).toList(),
                      onChanged: (_) {},
                    ),
                  )
                : Container();
          }),

my json structure as bellow.

 [
  {"distance": "12km","price": "200LKR",},
  {"distance": "2km","price": "100LKR",},
  {"distance": "132km","price": "340LKR",}
 ]

Answer

Constantin N. picture Constantin N. · Jun 25, 2019

This is how you must use map as list build. You have to precize the type you want to return. Especially you can do something like this

StreamBuilder(
      stream: _bLoc.getJsonArray,
      builder: (context, snapshot) {
        return snapshot.hasData
            ? new Container(
                width: 150,
                color: Theme.of(context).primaryColor,
                child: new DropdownButton<String>(
                  items: snapshot.data.map<DropdownMenuItem<String>>((value) =>
                     new DropdownMenuItem<String>(
                      value: value["distance"],
                      child: new Text(value["distance"]),
                    )
                  ).toList(),
                  onChanged: (_) {},
                ),
              )
            : Container();
      }),

PS You can catch some errors here when trying to get selected DropdownMenuItem. consider using custom generated list instead of mapping