Flutter 中的 Row 小部件:全面指南
在 Flutter 中,Row
是一個水平布局的小部件,用于將子控件沿著水平軸排列。Row
類似于 HTML 中的 div
標簽,但僅限于水平布局。它非常適合用來創建行式布局,如表單輸入、按鈕組、標簽欄等。
基礎用法
Row
最基本的用法是將多個控件水平排列:
Row(children: <Widget>[Container(width: 50.0, height: 50.0, color: Colors.red),Container(width: 50.0, height: 50.0, color: Colors.blue),// ... 更多的控件],
)
主軸對齊
Row
的 mainAxisAlignment
屬性用于控制子控件在主軸(水平軸)上的對齊方式:
開始對齊
Row(mainAxisAlignment: MainAxisAlignment.start,// ... 子控件
)
居中對齊
Row(mainAxisAlignment: MainAxisAlignment.center,// ... 子控件
)
兩端對齊
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,// ... 子控件
)
均勻分布
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly,// ... 子控件
)
交叉軸對齊
Row
的 crossAxisAlignment
屬性用于控制子控件在交叉軸(垂直軸)上的對齊方式:
Row(crossAxisAlignment: CrossAxisAlignment.center,// ... 子控件
)
間距和邊距
Row
的 mainAxisSize
屬性決定了 Row
的大小是否應該占據所有可用空間:
Row(mainAxisSize: MainAxisSize.min,// ... 子控件
)
通過 padding
屬性,可以為 Row
添加內邊距:
Row(padding: EdgeInsets.all(8.0),// ... 子控件
)
子控件間距
使用 spacing
屬性來設置子控件之間的水平間距:
Row(spacing: 10.0,children: List<Widget>.generate(5, (index) {return Container(width: 50.0, height: 50.0, color: Colors.primaries[index % Colors.primaries.length]);}).toList(),
)
子控件大小調整
使用 flex
屬性來設置子控件在 Row
中的彈性比例:
Row(children: <Widget>[Expanded(flex: 1,child: Container(color: Colors.red),),Expanded(flex: 2,child: Container(color: Colors.blue),),],
)
實例:水平表單
下面是一個使用 Row
創建水平表單的實例:
Row(children: <Widget>[Expanded(child: TextField(decoration: InputDecoration(labelText: 'Username',border: OutlineInputBorder(),),),),SizedBox(width: 16.0),Expanded(child: TextField(decoration: InputDecoration(labelText: 'Password',border: OutlineInputBorder(),),obscureText: true,),),],
)
實例:按鈕組
使用 Row
創建一組水平排列的按鈕:
Row(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[ElevatedButton(onPressed: () {},child: Text('Button 1'),),ElevatedButton(onPressed: () {},child: Text('Button 2'),),ElevatedButton(onPressed: () {},child: Text('Button 3'),),],
)
結語
Row
是 Flutter 中處理水平布局的核心小部件,它提供了豐富的對齊和間距選項,使得在 Flutter 應用中實現各種水平布局變得簡單而高效。掌握 Row
的使用,可以幫助你創建出既美觀又實用的布局界面。