edisom
edisom

Reputation: 13

Button text color change

I'm building simple quiz app as a learning project. I'd like to change only clicked button color. Now it changes colors of all buttons. I've tried to make a list of colors, so every button could take its color from the list.

class _AnwserButtonsState extends State<AnwserButtons> {
  Color color = Colors.black;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200,
      child: ListView(
        children: widget.anwsers
            .map(
              (anwser) => RaisedButton(
                child: Text(anwser, style: TextStyle(color: color)),
                onPressed: () => onPressed(anwser),
              ),
            )
            .toList(),
      ),
    );
  }

  onPressed(anwser) {
    setState(
      () {
        if (anwser == widget.properAnwser) {
          color = Colors.green;
        } else {
          color = Colors.red;
        }
      },
    );
  }
}

Upvotes: 0

Views: 327

Answers (2)

Can Karabag
Can Karabag

Reputation: 1751

You need an id value. You could use index when use ListView.builder.

ListView.builder(
            itemCount: widget.anwsers.length,
            itemBuilder: (BuildContext context, int index) {
return Column(
                  children: <Widget> [
RaisedButton(
                child: Text(widget.anwsers[index], style: TextStyle(color: color)),
                onPressed: () => onPressed(widget.anwsers[index], index),
              ),
            )
onPressed(anwser, index) {
    setState(
      () {
        if (anwser == widget.properAnwser[index]) {
          color = Colors.green;
        } else {
          color = Colors.red;
        }
      },
    );
  }
}

This could give you an idea. But my opinion is make a class that has answer, correct answer, color and id. Could be much easier and readable when use a class for this example.

Upvotes: 1

Aman Kataria
Aman Kataria

Reputation: 616

You'll be better off using ListView.builder, since you'll be able to control each RaisedButton through its index in the List

Useful Links:

https://api.flutter.dev/flutter/widgets/ListView/ListView.builder.html

https://medium.com/@DakshHub/flutter-displaying-dynamic-contents-using-listview-builder-f2cedb1a19fb

Upvotes: 0

Related Questions