Home > Enterprise >  Flutter > Unselect a RadioButton in a View.builder
Flutter > Unselect a RadioButton in a View.builder

Time:10-10

I am not finding any answer for my question so I am hoping to find someone who can help.

I have a GridView with text buttons. I can select the buttons, however I can't unselect any of them.

this is my code

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onLongPress: () => showDialog<String>(
      ),
      style: ButtonStyle(
          side: MaterialStateProperty.all(BorderSide(
              width: 5,
              color: widget.isSelected ? Colors.black : Colors.white)),
          shape: MaterialStateProperty.all(
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))),
          backgroundColor: MaterialStateProperty.all(widget.pickerColor),
          elevation: MaterialStateProperty.all(10)),
      onPressed: () {
        widget.selectedCard(widget.index); //This selects the cards, how to unselect (if Statements?)
      },
      child: FittedBox(
        fit: BoxFit.fitHeight,
        child: Text(
          widget.cardTitle,
          style: TextStyle(
            fontSize: 17,
            color: useWhiteForeground(widget.pickerColor)
                ? const Color(0xffffffff)
                : const Color(0xff000000),
          ),
        ),
      ),
    );
  }
}

This is the Grid

  @override
  Widget build(BuildContext context) {
    return Consumer<MyCardData>(
      builder: (context, cardData, child) {
        return Padding(
          padding: const EdgeInsets.all(10),
          child: GridView.builder(
            clipBehavior: Clip.none,
            itemBuilder: (context, index) {
              final card = cardData.cards[index];
              return MyCard(
                selectedCard,
                index: index,
                isSelected: _selectedCard == index,
                cardTitle: card.name,
                pickerColor: card.cardColor,
                deleteCallback: () {
                  cardData.deleteCallback(card);
                },
              );
            },
            itemCount: cardData.cardCount,
            gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: 150,
              childAspectRatio: 2.5 / 1,
              crossAxisSpacing: 0,
              mainAxisSpacing: 0,
            ),
          ),
        );
      },
    );
  }
}

enter image description here

feel free to use my git to see the full code

get from version control

CodePudding user response:

since you want to make a single selection, it will need a simple workaround.

int _selectedCard = -1;
selectedCard(index) {
   // this condition is when user press the same button
   // set the _selectedCard back into -1
   if (_selectedCard == index) {
    setState(() {
      _selectedCard = -1;
    });
  } else{
    setState(() {
      _selectedCard = index;
    });
  }
}
  • Related