Flutter: How to make a button expand to the size of its parent?

别说谁变了你拦得住时间么 提交于 2019-12-04 15:42:28

问题


I am trying to create square buttons, but Expanded doesn't seem to work the same as it does with containers. Take the following code for example

new Expanded(
 flex: 2,
   child: new Column(
     children: <Widget>[
       new Expanded(
         child:new Row(
           children: <Widget>[
             new Expanded(child: new MaterialButton(...)),
             new Expanded(child: new MaterialButton(....)),

             new Expanded(child: new Container(color: Colors.red)),
             new Expanded(child: new Container(color: Colors.green)),
           ]
         )
       )
     ],
   )
 )

 ....

It displays two buttons that are expanded horizontally, but not vertically. At the same time the containers will expand both horizontally and vertically. The same effect occurs if I do the following:

new Expanded(
 flex: 2,
   child: new Column(
     children: <Widget>[
       new Expanded(
         child:new Column(
           children: <Widget>[
             new Expanded(child: new MaterialButton(...)),
             new Expanded(child: new MaterialButton(....)),

             new Expanded(child: new Container(color: Colors.red)),
             new Expanded(child: new Container(color: Colors.green)),
           ]
         )
       )
     ],
   )
 )

 ....

Where I've changed the Row to Column. The buttons will expand vertically, but not horizontally, while the containers will do both.

Is there a way have my buttons expand to fit their parent both vertically and horizontally?


回答1:


Add the crossAxisAlignment property to your Row;

crossAxisAlignment: CrossAxisAlignment.stretch



回答2:


Wrapping with a ButtonTheme with minWidth: double.infinity allows to provide constraints

ButtonTheme(
  minWidth: double.infinity,
  child: MaterialButton(
    onPressed: () {},
    child: Text('Raised Button'),
  ),
),

or after https://github.com/flutter/flutter/pull/19416 landed

  MaterialButton(
    onPressed: () {},
    child: SizedBox.expand(
      width: double.infinity, 
      child: Text('Raised Button'),
    ),
  ),



回答3:


You can also try it

  1. Using SizedBox

    SizedBox(
      width: double.maxFinite, // set width to maxFinite
      child: RaisedButton(...),
    )
    
  2. Use MaterialButton's minWidth property.

    MaterialButton(
      minWidth: double.maxFinite, // set minWidth to maxFinite
      color: Colors.blue,
      onPressed: () {},
      child: Text("Button"),
    )
    


来源:https://stackoverflow.com/questions/49691052/flutter-how-to-make-a-button-expand-to-the-size-of-its-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!