【安卓】【Flutter 2-3】Flutter手把手教程UI布局和Widget——容器控件Container
作者 | 弗拉德
来源 | 弗拉德(公众号:fulade_me)
Container
我们先来看一下Container初始化的参数:
Container({Key key,
// 位置 居左、居右、居中
this.alignment,
// EdgeInsets Container的内边距
this.padding,
// 背景颜色
this.color,
// 背景装饰器
this.decoration,
// 前景装饰器
this.foregroundDecoration,
// 宽度
double width,
// 告诉
double height,
// 约束
BoxConstraints constraints,
// EdgeInsets Container的外边距
this.margin,
// 旋转
this.transform,
// 子控件
this.child,
// 裁剪Widget的模式
this.clipBehavior = Clip.none,
})
注意:
Container的color属性与属性decoration的color存在冲突,如果两个color都做了设置,默认会以decoration的color为准。- 如果我们没有给
Container设置width和height,Container会跟child的大小一样;假如我们没有设置child的时候,它的尺寸会极大化,尽可能的充满它的父Widget。
1. 最简单的Container
Container(child: Text("Fulade"),
color: Colors.red,
)
Container接收一个child参数,我们可以传入Text作为child参数,然后传入是一个颜色。
2. Padding
Container(child: Text("Pading 10"),
padding: EdgeInsets.all(10),
color: Colors.blue,
)
Padding是内边距,我们在这里设置了padding: EdgeInsets.all(10),也就是说Text距离Container的四条边的边距都是10。 
3. Margin
Container(child: Text("Margin 10"),
margin: EdgeInsets.all(10),
color: Colors.green,
)
Margin是外边距,我们在这里设置了margin: EdgeInsets.all(10),Container在原有大小的基础上,又被包围了一层宽度为10的矩形。
需要注意,绿色外围的白色区域也是属于Container的一部分。
4. transform
Container(padding: EdgeInsets.symmetric(horizontal: 15),
margin: EdgeInsets.all(10),
child: Text("transform"),
transform: Matrix4.rotationZ(0.1),
color: Colors.red,
)
transform可以帮助我们做旋转,Matrix4给我们提供了很多的变换样式。
5. decorationdecoration可以帮助我们实现更多的效果。例如形状、圆角、边界、边界颜色等。
Container(child: Text("Decoration"),
padding: EdgeInsets.symmetric(horizontal: 15),
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.all(Radius.circular(5)),
),
)

这里就是设置了一个圆角的示例,同样我们对BoxDecoration的color属性设置颜色,对整个Container的也是有效的。
6. 显示 Image
Container(height: 40,
width: 100,
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/flutter_icon_100.png"),
fit: BoxFit.contain,
),
),
)
BoxDecoration可以传入一个Image对象,这样就灵活了很多,Image可以来自本地也可以来自网络。
7. Border
Container(child: Text('BoxDecoration with border'),
padding: EdgeInsets.symmetric(horizontal: 15),
margin: EdgeInsets.all(5),
decoration: BoxDecoration(
borderRadius: BorderRadius.circula(12),
border: Border.all(
color: Colors.red,
width: 3,
),
),
)
使用border可以帮助我们做边界效果,还可以设置圆角borderRadius,也可以设置border的宽度,颜色等。
8. 渐变色
Container(padding: EdgeInsets.symmetric(horizontal: 20),
margin: EdgeInsets.all(20), //容器外填充
decoration: BoxDecoration(
gradient: RadialGradient(
colors: [Colors.blue, Colors.black, Colors.red],
center: Alignment.center,
radius: 5
),
),
child: Text(
//卡片文字
"RadialGradient",
style: TextStyle(color: Colors.white),
),
)
BoxDecoration的属性gradient可以接收一个颜色的数组,Alignment.center是渐变色开始的位置,可以从左上角、右上角、中间等位置开始颜色变化。

想体验以上的Container的示例的运行效果,可以到我的Github仓库项目flutter_app->lib->routes->container_page.dart查看,并且可以下载下来运行并体验。

以上是 【安卓】【Flutter 2-3】Flutter手把手教程UI布局和Widget——容器控件Container 的全部内容, 来源链接: utcz.com/a/105069.html

