flutter布局(一) - Container

前言

本文主要讲解flutter的布局的Container的基本使用和一些基础属性.

官方解释:
A convenience widget that combines common painting, positioning, and sizing widgets.

属性

下面列举了Container的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Container({
Key key,
this.alignment,
this.padding,
Color color,
Decoration decoration,
this.foregroundDecoration,
double width,
double height,
BoxConstraints constraints,
this.margin,
this.transform,
this.child,
})

属性说明:

key

Container唯一标识符,用于查找更新。

alignment

控制child的对齐方式,如果container或者container父节点尺寸大于child的尺寸,这个属性设置会起作用,有很多种对齐方式。

padding

decoration内部的空白区域,如果有child的话,child位于padding内部。padding与margin的不同之处在于,padding是包含在content内,而margin则是外部边界,设置点击事件的话,padding区域会响应,而margin区域不会响应。

color

用来设置container背景色,如果foregroundDecoration设置的话,可能会遮盖color效果。

decoration

绘制在child后面的装饰,设置了decoration的话,就不能设置color属性,否则会报错,此时应该在decoration中进行颜色的设置。

foregroundDecoration

绘制在child前面的装饰。

width

container的宽度,设置为double.infinity可以强制在宽度上撑满,不设置,则根据child和父节点两者一起布局。

height

container的高度,设置为double.infinity可以强制在高度上撑满。

constraints

添加到child上额外的约束条件。

margin

围绕在decoration和child之外的空白区域,不属于内容区域。

transform

设置container的变换矩阵,类型为Matrix4。

child

container中的内容widget。

官方代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Container(
constraints: BoxConstraints.expand(
height: Theme.of(context).textTheme.display1.fontSize * 1.1 + 200.0,
),
padding: const EdgeInsets.all(8.0),
color: Colors.teal.shade700,
alignment: Alignment.center,
child: Text('Hello World', style: Theme.of(context).textTheme.display1.copyWith(color: Colors.white)),
foregroundDecoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://www.example.com/images/frame.png'),
centerSlice: Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0),
),
),
transform: Matrix4.rotationZ(0.1),
)

代码效果

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import 'package:flutter/material.dart';

class LayoutDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Container'),
),
body: Container(
constraints: BoxConstraints.expand(
height: Theme.of(context).textTheme.display1.fontSize * 1.1 + 200.0,
),
padding: const EdgeInsets.all(8.0),
color: Colors.teal.shade700,
alignment: Alignment.center,
child: Text('Hello World',
style: Theme.of(context)
.textTheme
.display1
.copyWith(color: Colors.white)),
foregroundDecoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://www.example.com/images/frame.png'),
centerSlice: Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0),
),
),
transform: Matrix4.rotationZ(0.1),
));
}
}

void main() {
runApp(
new MaterialApp(
title: 'Flutter教程',
home: new LayoutDemo(),
),
);
}

大家有其他的更加快捷的方法,欢迎大家可以拿出来交流和讨论,谢谢。

写作是一个学习的过程,感谢您的赞助!
-------------本文结束感谢您的阅读!-------------