skip to Main Content

I am a beginner in Filter and I am typing these words with Google translator, my English is not good, please help and thank you very much.
Description of the problem
I have four clickable containers. I would like when the user clicks on them, only the background color of the current container will be changed to red, and the rest of the three containers will have their background color changed to blue.

I tried several times and for five days I couldn’t do anything unfortunately..
Where I used a variable to set the col value to be white as an initial value
This is the problem part

GestureDetector(
   onTap: () {
     setState(() {
      (col == Colors. white) ?col = Colors. red:col = Colors. blue;
          });
   },
   child: Container(
     alignment: Alignment. topLeft,
     decoration: BoxDecoration(
       color: color,
     ),
     child: Text(
       'S',
     ),
   ),
),`

I just want when clicking on the container, it changes color with a characteristic that differs from other containers

2

Answers


  1. You need to assign color with ternary operator like

    (col == Colors.white) ? col = Colors.red:col : col = Colors.blue;
    

    Or

    col =  col == Colors.white? Colors.red:col : Colors.blue;
    

    But if you are using single variable for all three container, it will change them all. Try using List instead.

    class CContainerChanged extends StatefulWidget {
      const CContainerChanged({super.key});
    
      @override
      State<CContainerChanged> createState() => _CContainerChangedState();
    }
    
    class _CContainerChangedState extends State<CContainerChanged> {
      List<Color> containerColors = [
        Colors.cyanAccent,
        Colors.deepPurpleAccent,
        Colors.deepOrangeAccent,
      ];
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: Center(
          child: Column(
            children: [
              for (int i = 0; i < containerColors.length; i++)
                Container(
                  width: 100,
                  height: 100,
                  color: containerColors[i],
                  child: TextButton(
                    onPressed: () {
                      setState(() {
                        containerColors[i] = Colors.red;
                      });
                    },
                    child: Text('Change color'),
                  ),
                ),
            ],
          ),
        ));
      }
    }
    
    

    If it is about selecting single container, it will

    
    class CContainerChanged extends StatefulWidget {
      const CContainerChanged({super.key});
    
      @override
      State<CContainerChanged> createState() => _CContainerChangedState();
    }
    
    class _CContainerChangedState extends State<CContainerChanged> {
      List<Color> containerColors = [
        Colors.cyanAccent,
        Colors.deepPurpleAccent,
        Colors.deepOrangeAccent,
      ];
    
      int? selectedIndex;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: Center(
          child: Column(
            children: [
              for (int i = 0; i < containerColors.length; i++)
                Container(
                  width: 100,
                  height: 100,
                  color:  selectedIndex == i ? Colors.red : containerColors[i],
                  child: TextButton(
                    onPressed: () {
                      setState(() {
                        selectedIndex = i;
                      });
                    },
                    child: Text('Change color'),
                  ),
                ),
            ],
          ),
        ));
      }
    }
    
    
    Login or Signup to reply.
  2. my solution by using a list view I have 5 containers when clicking on the container widget will update the current Index and change color

     class _MyHomePageState extends State<MyHomePage> {
      int currentIndex = 0;  // to save user click index 
      bool firstClick = false; // checking flag when first build and keep item color white 
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
            title: Text(widget.title),
          ),
          body: Center(
            child: ListView.builder(
                itemCount: 5,
                itemBuilder: (context, index) {
                  return InkWell(
                      onTap: () {
                        setState(() {
                          this.currentIndex = index;
                          this.firstClick = true;
                        });
                      },
                      child: firstClick
                          ? currentIndex == index
                              ? Container(
                                  // A fixed-height child.
                                  color: const Color(0xffeeee00), // Yellow
                                  height: 100.0,
                                  alignment: Alignment.center,
                                  child: Text("Content ${index}"),
                                )
                              : Container(
                                  // A fixed-height child.
                                  color: Colors.lightBlue, // Yellow
                                  height: 100.0,
                                  alignment: Alignment.center,
                                  child: Text('Content ${index}'),
                                )
                          : Container(
                              // A fixed-height child.
                              color: Colors.white, // Yellow
                              height: 100.0,
                              alignment: Alignment.center,
                              child: Text("Content ${index}"),
                            ));
                }),
          ),
        );
      }
    }
    

    Have Nice Day 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search