danu
danu

Reputation: 1188

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",}
 ]

Upvotes: 9

Views: 17458

Answers (2)

Constantin N.
Constantin N.

Reputation: 2839

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

Upvotes: 23

Ketan
Ketan

Reputation: 1015

As error tells you are casting concrete type to dynamic. You may want to use .map<TYPE>() to cast to String. See the end of this thread - https://github.com/flutter/flutter/issues/18979

Upvotes: 3

Related Questions