Joe
Joe

Reputation: 343

Get string value from togglebutton

I have created Togglebuttons composed of three options, each with a different text. The user can only select one option from the three, identifying their gender in this case. I would like to pass the selected option as a String to the next page.

How can I get the value from the selection as a string?

My code so far:

List<bool> isSelected;

// Initialize Set state for gender button toggle
@override
void initState() {
  isSelected = [false, false, false];
  super.initState();
}


final genderToggleButtons = Container(
  width: mq.size.width,
  padding: EdgeInsets.zero,
  decoration: BoxDecoration(
    color: AppTheme.define().accentColor,
    borderRadius: BorderRadius.all(
      Radius.circular(10.0),
    ),
  ),
  child: LayoutBuilder(
    builder: (context, constraints) {
      return ToggleButtons(
        renderBorder: false,
        color: Colors.white,
        constraints: BoxConstraints.expand(width: constraints.maxWidth / 3),
        fillColor: AppTheme.define().primaryColor,
        selectedColor: Colors.white,
        borderRadius: BorderRadius.circular(10),
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(27.0),
            child: Text(
              "Male",
              style: TextStyle(
                fontSize: 17.0,
                fontFamily: 'RobotoRegular',
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(1.0),
            child: Text(
              "Female",
              style: TextStyle(
                fontSize: 17.0,
                fontFamily: 'RobotoRegular',
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(1.0),
            child: Text(
              "Non-Binary",
              style: TextStyle(
                fontSize: 17.0,
                fontFamily: 'RobotoRegular',
              ),
            ),
          ),
        ],
        onPressed: (int index) {
          setState(
            () {
              for (int buttonIndex = 0;
                  buttonIndex < isSelected.length;
                  buttonIndex++) {
                if (buttonIndex == index) {
                  isSelected[buttonIndex] = true;
                  // Choosing gender will enable the next button
                  _enableBtn = true;
                } else {
                  isSelected[buttonIndex] = false;
                }
              }
            },
          );
        },
        isSelected: isSelected,
      );
    },
  ),
);

Upvotes: 0

Views: 604

Answers (1)

Loren.A
Loren.A

Reputation: 5575

Anytime you want to start passing data around to pages, which is really any real app, you'll want to implement a state management solution. Here's how I'd do it using GetX.

Similar solutions are available with pretty much any other state management ie. Provider, Riverpod, Bloc etc...

Here's a class where the string will get stored and updated based on the ToggleButton selection.

class Controller extends GetxController {
  String gender = '';

  void selectGender(int index) {
    if (index == 0) {
      gender = 'male';
    } else if (index == 1) {
      gender = 'female';
    } else if (index == 2) {
      gender = 'non-binary';
    }
    update();
  }
}

Throw this in your build method of the page with the ToggleButton. This initializes the GetxController.

final controller = Get.put(Controller());

The for loop of your onPressed now looks like this

 for (int buttonIndex = 0;
      buttonIndex < isSelected.length;
      buttonIndex++) {
     if (buttonIndex == index) {
      isSelected[buttonIndex] = true;
      controller.selectGender(index); // calling method from GetX Controller class
      _enableBtn = true;
     } else {
       isSelected[buttonIndex] = false;
       }
      }

And here's an example of how you'd access that String from anywhere else in the app. Same concept applies to any other variable that lives in that class.

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final controller =
        Get.find<Controller>(); // finding same instance of controller
    return Scaffold(
      body: Center(
        // this GetBuilder widget rebuilds based on any updates to the GetX variable inside
        child: GetBuilder<Controller>(
          builder: (_) {
            return Text(controller.gender);
          },
        ),
      ),
    );
  }
}

Upvotes: 1

Related Questions