Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter dynamically created FilterChip not updated on onSelected()

Tags:

flutter

dart

I am dynamically generating FilterChips in the initState function of the StateFull widget, as below.

List<Category> categories;
List<FilterChip> chips;
(...)

in initState() : 

 for (Category c in categories) {
        chips.add(FilterChip(
          label: chipText(context, c.name),
          onSelected: (val) {
            print(val); // val is always false !
            c.enabled = !c.enabled;

            print(categories); // this is ok, categories values are perfectly updated
            setState(() {});
          },
          selected: c.enabled, // however, the filterchip selected state does not reflect c.enabled value changes
          selectedColor: accentColor(context),
        ));
      }

When I click the filterchip, the value of the Categoy is perfectly updated, however the chip selection state does not change. Does anyone understands why ?

To answer how I then use chips: this is in the build function as follow:

@override
  build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Wrap(
        children: chips
       )
like image 975
Emmanuel Cohen-Laroque Avatar asked Aug 30 '25 17:08

Emmanuel Cohen-Laroque


1 Answers

pskink gave the perfect answer: thanks!

Here is the working code, where chips are dynamically created directly in the build function:

  @override
  build(BuildContext context) {
    if (categories != null) {
      chips = categories
          .map((c) => FilterChip(
                label: chipText(context, c.name ?? ""),
                onSelected: (val) {
                  setState(() {
                    c.enabled = val;
                  });
                  updateSelection();
                },
                selected: c.enabled,
                selectedColor: accentColor(context),
              ))
          .toList();
    }
    return SliverToBoxAdapter(
      child: Wrap(
          children: chips
like image 99
Emmanuel Cohen-Laroque Avatar answered Sep 02 '25 10:09

Emmanuel Cohen-Laroque