
Container是一个多功能容器,可以设置宽高、背景色、圆角边框等样式属性,同时支持内外边距和对齐方式。示例中展示了如何将文本包装在红色背景的Container内:
Container(
child: Text('Container(容器)在UI框架中是一个很常见的概念,Flutter也不例外。'),
padding: EdgeInsets.all(18.0),
margin: EdgeInsets.all(44.0),
width: 180.0,
height:240,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(10.0),
),
)Padding专门用于设置子Widget的内边距,支持通过EdgeInsets灵活定义各方向间距:
Padding(
padding: EdgeInsets.all(44.0),
child: Text('Container(容器)在UI框架中是一个很常见的概念,Flutter也不例外。'),
);Center用于将子Widget居中显示,通常需要父容器提供足够空间。示例展示了文本居中效果:
Scaffold(
body: Center(child: Text("Hello"))
);Row和Column分别用于水平和垂直排列子Widget。Expanded可分配剩余空间。以下代码演示了Row和Column的用法:
Row(
children: <Widget>[
Container(color: Colors.yellow, width: 60, height: 80,),
Container(color: Colors.red, width: 100, height: 180,),
Container(color: Colors.black, width: 60, height: 80,),
Container(color: Colors.green, width: 60, height: 80,),
],
);
Column(
children: <Widget>[
Container(color: Colors.yellow, width: 60, height: 80,),
Container(color: Colors.red, width: 100, height: 180,),
Container(color: Colors.black, width: 60, height: 80,),
Container(color: Colors.green, width: 60, height: 80,),
],
);Stack允许子Widget层叠显示,配合Positioned可精确控制位置。示例中展示了文本和图片的层叠效果:
Stack(
children: <Widget>[
Image.network('https://example.com/image.jpg'),
Positioned(
bottom: 10,
right: 10,
child: Text('Layer Text'),
),
],
);使用Container时注意其只能包含一个子Widget,多子场景需用Row/Column等包装后再放入。
Row/Column默认不会滚动,内容超出需配合SingleChildScrollView或ListView。
Expanded需作为Row/Column的直接子Widget使用,通过flex参数分配剩余空间比例。
Stack的定位依赖于父容器尺寸,需确保父容器提供足够空间。