Selected ChoiceChip in ListView unselects itself, when scrolling down the ListView

353 views Asked by At

In my app I have created a ListView (horizontal) with some ChoiceChips. For example, when I select the first ChoiceChip, it turns blue and is selected. But if I then scroll the ListView once and come back to my selected ChoiceChip at the beginning, it is no longer selected. What could be the reason for this? Here is the code:

import 'package:flutter/material.dart';

class MyChoiceChip extends StatefulWidget {
  MyChoiceChip({this.label});

  final String label;

  @override
  _MyChoiceChipState createState() => _MyChoiceChipState();
}

class _MyChoiceChipState extends State<MyChoiceChip> {

  int _value = 1;

  @override
  Widget build(BuildContext context) {
     return Wrap(
      children: List<Widget>.generate(
        1,
            (int index) {
          return Padding(
            padding: const EdgeInsets.only(right: 10),
            child: ChoiceChip(
              label: Text(widget.label),
              selected: _value == index,
              onSelected: (bool selected) {
                setState(() {
                  _value = selected ? index : null;
                  if(widget.label == "Instrumentalist"){

                  }
                });
              },
            ),
          );
        },
      ).toList(),
    );
  }}
1

There are 1 answers

0
Prabhanshu Tiwari On

remove wrap

and use listview.builder