Expand toggle buttons to parent container width

Viewed 4149

Is there any way to dynamically expand toggle buttons to parent container width without hard coding anything. I found one answer to that which uses MediaQuery of context which only works well for full screen width. I also tried to wrap the buttons in expanded widget but that throws an error

Container(
  width: 150.0, // hardcoded for testing purpose 
  child: ToggleButtons(
    constraints:
        BoxConstraints.expand(width: MediaQuery.of(context).size.width), // this doesn't work once inside container unless hard coding it
    borderRadius: BorderRadius.circular(5),
    children: [
      ShapeToggleButton(
        text: 'Option1',
      ),
      ShapeToggleButton(
        text: 'Option2',
      ),
    ],
    isSelected: [true, false],
    onPressed: (index) {},
  ),
);
1 Answers

As suggested by psink in comment above answer is to wrap it in LayoutBuilder

        Container(
              width: 150.0, // hardcoded for testing purpose
              child: LayoutBuilder(builder: (context, constraints) {
        return ToggleButtons(
          renderBorder: false,
          constraints:
              BoxConstraints.expand(width: constraints.maxWidth / 2), //number 2 is number of toggle buttons
          borderRadius: BorderRadius.circular(5),
          children: [
            Text(
              'Option1',
            ),
            Text(
              'Option2',
            ),
          ],
          isSelected: [true, false],
          onPressed: (index) {},
        );
      })))
Related