Search code examples
colorsflutteronclickandroid-chipsonpress

OnPressed Set activeColor to a button of a list, and set inactiveColor to others btns - Flutter


I have a list of Chips, and I want them to change color when user click on them.

For instance if I click on the first Chip its color become black, and every other chips are grey. Then if I click on the second Chip its color become black and first Chip color become grey and so on.

I can't find a beautiful/simple way to do this, have you any ideas ?

Thanks a lot


Solution

  • Here is how you can do it:

      Widget _myChip(int number, String name) {
        return new Padding(
          padding: const EdgeInsets.all(8.0),
          child: new InkWell(
            child: new Chip(
                label: new Text(name,
                style: new TextStyle(
                  color: selectedChip == number ? Colors.white : Colors.black
                ),),
                backgroundColor:
                    selectedChip == number ? Colors.black : Colors.grey),
            onTap: () {
              setState(() {
                selectedChip = number;
              });
            },
          ),
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text('Stackoverflow'),
          ),
          body: new Column(
            children: <Widget>[
              _myChip(1, 'Arnold'),
              _myChip(2, 'Sylvester'),
              _myChip(3, 'Priscilla'),
              _myChip(4, 'Parge'),
              _myChip(5, 'Something'),
            ],
          ),
        );
      }
    

    You need to give chips a unique number to identify and use inline if to change the color of the chips.