Home > Software engineering >  How to make a container as a radio button in Flutter and make sure it doesn't deselect
How to make a container as a radio button in Flutter and make sure it doesn't deselect

Time:01-25

I have used a package enter image description here

CodePudding user response:

You can use List of button text and keep tract of selectedIndex.

Run on dartPad

 int? _selectedValueIndex;
  List<String> buttonText = ["ForSale", "For rent"];

  Widget button({required String text, required int index}) {
    return InkWell(
      splashColor: Colors.cyanAccent,
      onTap: () {
        setState(() {
          _selectedValueIndex = index;
        });
      },
      child: Container(
        padding: const EdgeInsets.all(12),
        color: index == _selectedValueIndex ? Colors.blue : Colors.white,
        child: Text(
          text,
          style: TextStyle(
            color: index == _selectedValueIndex ? Colors.white : Colors.black,
          ),
        ),
      ),
    );
  }

Inside build method to use this,

 Row(
  children: [
    ...List.generate(
      buttonText.length,
      (index) => button(
        index: index,
        text: buttonText[index],
      ),
    )
  ],
),
  •  Tags:  
  • Related