Thoxh
Thoxh

Reputation: 149

Use dynamic list in DropDownButton | Flutter

my problem is following:

class Data {
  final String? image, title, link;
  final Color? color;

  Data({
    this.title,
    this.image,
    this.link,
    this.color,
  });
}


List dataList = [
  Data(
      title: "XXX",
      image: "XXX",
      link: "XXX",
      color: XXX),

...

I have this class and list to store my data and however I'm used that way the first time to learn something new. Now I have the problem that I'm totally failing to create a DropDownButton with the data from my list because of the Data() I've in there.

I tried something like this:

@override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: DropdownButton<String>(
          items: dataList.map((Map map) {
              return new DropdownMenuItem<String>(
                value: map["title"].toString(),
                child: new Text(
                  map["name"],
                ),
              );
            }).toList(),
        ),
      ),
    );
  }
}

But I was sure that this option wont work for my example. I think there is now way out to ask you for help. So my exact question is, how can I create a DropDownMenu/Button, where the title of all my Data classes is displayed in a list. I appreciate your help, thanks.

Upvotes: 0

Views: 1807

Answers (1)

Mudassir
Mudassir

Reputation: 806

Your list is of generic type Data, but you are treating it as a Map.

@override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: DropdownButton<String>(
          items: dataList.map((data) {
              return DropdownMenuItem<String>(
                value: data.title.toString(),
                child: Text(
                  data.name,
                ),
              );
            }).toList(),
        ),
      ),
    );
  }
}

It should work now.

Upvotes: 1

Related Questions