Home > Back-end >  change button colors when it's clicked on Flutter
change button colors when it's clicked on Flutter

Time:09-23

Here is a builder that I will call 11 times, and I want to change the other 10 buttons color to grey when I click in one of the 11 buttons, how do I do that?

Widget buildElevatedButton(int number, Color buttonColor) {
 return Padding(
   padding: EdgeInsets.all(5.0),
    child: Column(
     children: <Widget>[
       ElevatedButton(
         onPressed: () {},
         child: Text(
               "$number",
                textAlign: TextAlign.center,
          ),
         style: ElevatedButton.styleFrom(
           shadowColor: Colors.grey,
           primary: buttonColor,
           minimumSize: Size(70, 70),
           shape: RoundedRectangleBorder(
             borderRadius: BorderRadius.circular(15.0),
            ),
             textStyle: TextStyle(
             fontSize: 40,
             fontWeight: FontWeight.bold,
           ),
         ),
       ),
     ],
   ),
 );

}

CodePudding user response:

You can create a Map for checking the state

Map<int, bool> buttons = {
    0: false,
    1: false,
    2: false,
    3: false,
    4: false,
  };

and then inside your builder when the button is clicked toggle the Map buttons and change state to true

ListView.builder(
          itemCount: buttons.length,
          itemBuilder: (context, index) => ElevatedButton(
            onPressed: () {
              setState((){
                buttons[index] = true;
              });
              buttons.forEach((k, v) {
                if(index != k){
                  buttons[k]=false;
                }
              });
            },
            style: ButtonStyle(
              backgroundColor: buttons[index]?MaterialStateProperty.all(Colors.blue): MaterialStateProperty.all(Colors.grey),
            ),
            child: Text(
              "Button $index",
            ),
          ),
        ),

CodePudding user response:

I think what you are looking for is a Stateless Widget class that takes a callback, which is passed to the button. The state of the buttons needs to be maintained by the root widget (you lift the state up). The flutter documentation on state are quite good: https://flutter.dev/docs/development/ui/interactive

Here is a working example:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _selectedButton = null;
  void setSelectedButton(int index) {
    setState(() {
      _selectedButton = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Wrap(children: [
          for (int i = 0; i < 10; i  )
            CustomElevatedButton(
                i,
                _selectedButton == null
                    ? Colors.red
                    : _selectedButton == i
                        ? Colors.red
                        : Colors.grey, () {
              setSelectedButton(i);
            }),
        ]),
      ),
    );
  }
}

class CustomElevatedButton extends StatelessWidget {
  final int number;
  final Color buttonColor;
  final void Function() onPressed;
  CustomElevatedButton(this.number, this.buttonColor, this.onPressed);
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(5.0),
      child: Column(
        children: <Widget>[
          ElevatedButton(
            onPressed: onPressed,
            child: Text(
              '${number   1}',
              textAlign: TextAlign.center,
            ),
            style: ElevatedButton.styleFrom(
              shadowColor: Colors.grey,
              primary: buttonColor,
              minimumSize: Size(70, 70),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15.0),
              ),
              textStyle: TextStyle(
                fontSize: 40,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Explanation: The MyHomePage stateful widget is the parent and maintains the state (i.e. it keeps track of which button is pressed). The child is a stateless widget with your custom button. The state is lifted up to the place where the buttons are actually built.

  • Related