Zuher Abud Said
Zuher Abud Said

Reputation: 745

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

I have used a package group_button 4.2.1 but once i select the textfields the radio buttons deselect and i have to select again, i have tried using the controller property of the Widget but i didn't get it to work.

I was thinking if i can make a container from scratch that is a radio button and can retain the value once i finish filling the form to be submitted to my firestore database.

enter image description here

Upvotes: 2

Views: 4553

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

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],
      ),
    )
  ],
),

Upvotes: 5

Related Questions