John Doah
John Doah

Reputation: 1999

Generating a list of choice chips inside a column

I have an array of strings, which I'm trying to display as choice chips. I saw the doc of the flutter website (here: https://api.flutter.dev/flutter/material/ChoiceChip-class.html) and I copied it to try and use it in my application.

This is what I have:

      Widget categoriesList(BuildContext context) {
    return Wrap(
      children: [
        List<Widget>.generate(
          options.length,
          (int idx) {
            return ChoiceChip(
                label: Text(options[idx]),
                selected: _value == idx,
                onSelected: (bool selected) {
                  setState(() {
                    _value = selected ? idx : null;
                  });
                });
          },
        ).toList()
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Title(),
          categoriesList(context),
        ],
      ),
    );
  }
}

The problem is that I always get in categoriesList this error:

The element type 'List<Widget>' can't be assigned to the list type 'Widget'.

I tried to search, and this error seems really common, but I can't really tell what's wrong with the piece of code I have - even after seeing answers that was flagged as correct. And also, this piece of code is from the flutter docs, so I guess it should be fine.

What am I missing?

Upvotes: 2

Views: 5446

Answers (1)

Pathik Patel
Pathik Patel

Reputation: 1490

.toList() automatically generates the List, I can see theres [] in which you parsed the list of widgets.

Simply remove the [], like below:

return Wrap(
  children: List<Widget>.generate(
    options.length,
    (int idx) {
      return ChoiceChip(
          label: Text(options[idx]),
          selected: _value == idx,
          onSelected: (bool selected) {
            setState(() {
              _value = selected ? idx : null;
            });
          });
    },
  ).toList(),
);

Upvotes: 3

Related Questions