Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - FlatButton Fill available horizontal space

I'm trying to have a UI in such a way that the number of buttons in a row changes depending on available information. More specifically, there will always be one FlatButton that links to an external page, but if a download link is also provided, then there will be a second FlatButton in the row.

On the website that currently exists, we have this working for one button versus two buttons, but I can't get the one button to horizontally expand to fill the available space.

At the moment, I add the FlatButtons to a List<Widget> variable that I pass as the children for a row. I have tried using Flex -> Expanded, SizedBox.expand, CrossAxisAlignment.stretch and every solution I have found on this site so far to get it to expand, but every solution I have tried have all resulted in forced infinite width or unbounded width or non-zero flex but incoming width constraints are unbounded.

Here's my code in the build method as it currently stands:

List<Widget> fullTextDownloadBtns = new List();
if (this.fullArticleUrl != null && this.fullArticleUrl.isNotEmpty) {
  fullTextDownloadBtns.add(
    FlatButton(
      color: Color(0x66629c44),
      onPressed: _openFullArticle,
      child: Text(
        "Full Article",
        style: TextStyle(color: Color(0xff629c44)),
      ),
    )
  );
}

if (this.downloadUrl != null && this.downloadUrl.isNotEmpty) {
  fullTextDownloadBtns.add(
    FlatButton(
      color: Color(0x664d69b1),
      onPressed: _download,
      child: Text(
        "Download",
        style: TextStyle(color: Color(0xff4d69b1)),
      ),
    )
  );
}

return Scaffold(
    appBar: AppBar(
      backgroundColor: Color(0xff0096b0)
    ),
    body: SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // ...related image, title

          Container(
            padding: EdgeInsets.all(15.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: fullTextDownloadBtns,
            ),
          ), // Read full article & download PDF

          // ... Authors, excerpt/description, like/share buttons, comments
        ],
      )
    ),
  );
like image 304
MattChris Avatar asked May 13 '26 09:05

MattChris


1 Answers

Wrapping your buttons with Expanded is the way to go here (I tried it with your code) :

Row(
  children: [
    Expanded(
      child: FlatButton(onPressed: (){},
        child: Text("1")),
    ),
    Expanded(
      child: FlatButton(onPressed: (){},
        child: Text("2")),
    )
  ],
),

By the way, since the SDK 2.2.2 (in your pubspec.yaml), you can use conditions within the children list :

children: [
  if(true == true)
  FlatButton(
    onPressed: (){},
    child: Text("1")),
],
like image 125
MickaelHrndz Avatar answered May 15 '26 06:05

MickaelHrndz