# 紧约束

本文作者:阳九五 (opens new window)

本站地址:https://blog.56321654.xyz (opens new window)

松约束(tight constraints)是指在布局过程中,给定的约束条件使得子组件的尺寸被精确地确定,通常等于某个特定的值。

尺寸是固定的

# ConstrainedBox 约束组件

  • constraints 通过 maxWidth maxHeight ,来设置子组件最大约束
void main() {
  runApp(build());
}

Widget build() {
  return MaterialApp(
    home: Scaffold(
      body: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(
            maxWidth: 200,
            maxHeight: 200,
          ),
          child: Container(
            color: Colors.amber,
            width: 50,
            height: 50,
          ),
        ),
      ),
    ),
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

显示了一个 50 x 50 的 Container

Image

  • 我们加上 minWidth minHeight ,来设置子组件最小约束
void main() {
  runApp(build());
}

Widget build() {
  return MaterialApp(
    home: Scaffold(
      body: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(
            minWidth: 100,
            minHeight: 100,
            maxWidth: 200,
            maxHeight: 200,
          ),
          child: Container(
            color: Colors.amber,
            width: 10,
            height: 10,
          ),
        ),
      ),
    ),
  );
}
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

这时候 尺寸强制被设置为了 100 * 100

Image

  • 查看约束情况

Image

# 紧约束定义

它的最大/最小宽度是一致的,高度也一样。

  • 通过 BoxConstraints.tight 可以设置紧约束
void main() {
  runApp(build());
}

Widget build() {
  return MaterialApp(
    home: Scaffold(
      body: Center(
        child: ConstrainedBox(
          constraints: BoxConstraints.tight(const Size(100, 100)),
          child: Container(
            color: Colors.amber,
            width: 10,
            height: 10,
          ),
        ),
      ),
    ),
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Image

  • 宽高约束都被设置成了 100

Image

# 参考

最近更新: 7/29/2025, 9:40:27 AM