Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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",}
 ]
like image 520
danu Avatar asked Jun 25 '19 15:06

danu


1 Answers

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

like image 114
Constantin N. Avatar answered Sep 22 '22 15:09

Constantin N.