Search code examples
flutterdartflutter-layout

When clicking on the card in Flutter, I want to give a border color and the card can be selected


  class PopUpCard extends StatefulWidget {
  final String title;
  const PopUpCard({super.key, required this.title});
}
  Container(
              child: Card(
                child: Center(
                    child: Text(
                  widget.title,
                
                )),
              ),

I'm calling the widget I created on my homepage.

 Row(
                children: const [
                  PopUpCard(
                    title: '9',
                  ),

enter image description here

For example, when the card number 9 is clicked, as in the image, I want a red border around it.


Solution

  • first, declare a boolean variable at the top of that widget:

    bool isSelected = false;
    

    then set the border on the container based on that bool:

     Container(
          height: 80,
          width: 80,
          decoration: BoxDecoration(
           border: isSelected ? Border.all(color: Colors.red, width: 2,) : null
           ),
          child: Card(
            color: Color.fromARGB(255, 19, 85, 144),
            child: Center(
                child: Text(
              widget.title,
              style: GoogleFonts.poppins(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold),
            )),
          ),
    

    then wrap your widget with GestureDetector widget, toggle that isSelected in the onTap method property, and update the state

     GestureDetector(
        onTap: () {
        isSelected = !isSelected;
        SetState(() {});
        },
        child: Container(
              height: 80,
              width: 80,
              decoration: BoxDecoration(
               border: isSelected ? Border.all(color: Colors.red, width: 2,) : null
               ),
              child: Card(
                color: Color.fromARGB(255, 19, 85, 144),
                child: Center(
                    child: Text(
                  widget.title,
                  style: GoogleFonts.poppins(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold),
                )))),