Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand multiple widgets to full width in a row in Flutter?

Tags:

flutter

dart

I'm trying to get a button in Flutter to expand to its parent width and dynamically expand as more widgets are added. For example, if there are two buttons in a row, they will expand to 50% width each, for three buttons 33% etc.

I tried width: Double.infinite which works for a single button. Understandably, this would not work for multiple buttons since the width is unconstrained and Flutter does not know how to size the element.

I tried all sorts of properties, SizedBox, crossAxisAlignment, Expanded but they don't seem to work.

What I am trying to achieve would be something similar to this: https://bulma.io/documentation/columns/basics/ - a flex based column layout.

App.dart

class App extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
      // theme: WhisperyTheme,
      // theme: ThemeData(fontFamily: "Overpass"),
      home: Scaffold(
        body: Center(
          child: Column(
            children: <Widget>[
              LongButton(
                onTap: () => null,
                text: "Primary Button",
              ),
              Row(
                children: <Widget>[
                  LongButton(
                    onTap: () => null,
                    text: "Secondary Button",
                  ),
                  LongButton(
                    onTap: () => null,
                    text: "Secondary Button",
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

Button.dart

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(maxHeight: 40.0),
      margin: EdgeInsets.all(15),
      height: 40.0,
      decoration: BoxDecoration(border: Border.all(width: 1.5)),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: _onTap,
          child: Center(
            child: Text(_text),
          ),
        ),
      ),
    );
  }

enter image description here

like image 934
Carrein Avatar asked Jan 26 '23 20:01

Carrein


1 Answers

You can wrap your button with Flexible widget, its default flex parameter is 1, so the space will be divided equally between all the widgets:

Row(
  children: <Widget>[
    Flexible(
      child: LongButton(
        onTap: () => null,
        text: 'Secondary Button',
      ),
    ),
    Flexible(
      child: LongButton(
        onTap: () => null,
        text: 'Secondary Button',
      ),
    ),
  ],
)
like image 156
Kirill Bubochkin Avatar answered Feb 02 '23 22:02

Kirill Bubochkin