它是由衆多容器類Widget(DecoratedBox、ConstrainedBox、Transform、Padding、Align等)組合成的Widget,因此它的功能能夠說集衆家之特性ide
它是Stack佈局內進行定位的Widget,與CSS中 position:absolute;
類似佈局
在flutter中,Container容器通常默認是佔滿整個空間。當Positioned使用Container,會出現什麼狀況呢?post
....
....
@override
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
child: Stack(
children: <Widget>[
Positioned(
//主要分析的Container對象
child: Container(
//_keyRed 申明爲全局變量 GlobalKey _keyRed = GlobalKey();
//用key綁定Container
key: _keyRed,
decoration: BoxDecoration(color: Colors.yellow),
child: Row(
children: <Widget>[
],
),
),
),
Positioned(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
MaterialButton(
elevation: 5.0,
padding: EdgeInsets.all(15.0),
color: Colors.grey,
child: Text("Get Sizes"),
onPressed: _getSizes,
),
MaterialButton(
elevation: 5.0,
color: Colors.grey,
padding: EdgeInsets.all(15.0),
child: Text("Get Positions"),
onPressed: _getPositions,
),
],
)),
],
),
);
//獲取Positioned中Container渲染位置
_getPositions() {
final RenderBox renderBoxRed = _keyRed.currentContext.findRenderObject();
final positionRed = renderBoxRed.localToGlobal(Offset.zero);
print("POSITION of Red: $positionRed ");
}
//獲取Positioned中Container大小
_getSizes() {
final RenderBox renderBoxRed = _keyRed.currentContext.findRenderObject();
final sizeRed = renderBoxRed.size;
print("SIZE of Red: $sizeRed");
}
複製代碼
I/flutter (27566): SIZE of Red: Size(360.0, 0.0)
I/flutter (27566): POSITION of Red: Offset(0.0, 0.0)
複製代碼
給Container加上height: 50.0
ui
I/flutter (27566): SIZE of Red: Size(360.0, 50.0)
I/flutter (27566): POSITION of Red: Offset(0.0, 0.0)
複製代碼
bottom:0
Container又消失了,加上 bottom:0
定位的數值後,就比如HTML中塊級元素被絕對定位position:absolute;
默認寬高的數值爲0I/flutter (27566): SIZE of Red: Size(0.0, 50.0)
I/flutter (27566): POSITION of Red: Offset(0.0, 542.0)
複製代碼
給Container加width或者加子元素spa
....
....
//用key綁定Container
key: _keyRed,
decoration: BoxDecoration(color: Colors.yellow),
child: Row(
children: <Widget>[
Text('222 '),
Text('333'),
],
),
複製代碼
I/flutter (27566): SIZE of Red: Size(203.0, 50.0)
I/flutter (27566): POSITION of Red: Offset(0.0, 542.0)
複製代碼
試試給Container加邊距
margin: EdgeInsets.only(bottom: 50.0,right: 10.0)
I/flutter (27566): SIZE of Red: Size(213.0, 100.0)
I/flutter (27566): POSITION of Red: Offset(0.0, 492.0)
// padding: EdgeInsets.only(top: 50.0,left: 10.0),`
I/flutter (27566): SIZE of Red: Size(213.0, 50.0)
I/flutter (27566): POSITION of Red: Offset(0.0, 542.0)
複製代碼
Align 代替 Positioned3d
Align(
//對齊底部
alignment: Alignment.bottomCenter,
child: Container(
key: _keyRed,
decoration: BoxDecoration(color: Colors.yellow),
child: Row(
children: <Widget>[
Text('222 '),
Text('333'),
],
),
),
),
複製代碼
用Align容器讓Container的寬度鋪滿可是高度仍是默認爲0,因此增長子元素效果以下:code