文章

SizedBox-shrink

SizedBox.shrink()

SizedBox-shrink

SizedBox.shrink()

SizedBox.shrink() 是 Flutter 中一个非常实用的组件,下面详细介绍它的作用和日常用法:

作用

SizedBox.shrink() 创建一个尺寸为 0×0 的空盒子,它:

  • 不占用任何布局空间
  • 不渲染任何内容
  • 是最轻量级的空组件

日常用法

1. 条件渲染的空状态(最常用)

1
2
3
4
5
Widget build(BuildContext context) {
  return isLoading 
    ? CircularProgressIndicator()
    : SizedBox.shrink();
}

2. 替代老的 Container()

1
2
3
4
5
// 不推荐 - Container() 有额外的绘制开销
condition ? MyWidget() : Container()

// 推荐 - SizedBox.shrink() 更轻量
condition ? MyWidget() : SizedBox.shrink()

3. 作为默认值或占位符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyWidget extends StatelessWidget {
  final Widget? child;

  const MyWidget({this.child});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        child ?? SizedBox.shrink(), // 如果没有子组件就返回空
        // ... 其他组件
      ],
    );
  }
}

4. 在 Row/Column 中条件渲染子项

1
2
3
4
5
6
7
Column(
  children: [
    if (showTitle) Text('标题'),
    shouldShowDivider ? Divider() : SizedBox.shrink(),
    Text('内容'),
  ],
)

5. 替代空的 Center 或 Padding

1
2
3
4
5
// 不推荐
condition ? MyWidget() : Center()

// 推荐 - 如果不需要居中效果
condition ? MyWidget() : SizedBox.shrink()

与其他空组件的对比

组件尺寸渲染开销适用场景
SizedBox.shrink()0×0最小推荐 条件渲染的空状态
Container()父级约束中等需要装饰效果时
SizedBox()0×0同 shrink(),但代码更长
Offstage()保持布局中等需要保留组件状态时
Visibility(visible: false)保持布局中等需要动画或保留状态时

实际示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 用户头像条件渲染
Widget buildAvatar() {
  return user?.avatarUrl != null 
    ? CircleAvatar(backgroundImage: NetworkImage(user!.avatarUrl!))
    : SizedBox.shrink();
}

// 错误消息条件显示
Widget buildErrorMessage() {
  return errorMessage != null
    ? Text(errorMessage!, style: TextStyle(color: Colors.red))
    : SizedBox.shrink();
}

// 列表空状态
Widget buildList() {
  return items.isEmpty
    ? const Text('暂无数据')
    : ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, index) => ListTile(title: Text(items[index])),
    );
}

总结

**优先使用**** ****SizedBox.shrink()** 当你需要:

  • 条件渲染的空状态
  • 轻量级的占位符
  • 避免不必要的布局计算

它的简洁性和高性能使其成为 Flutter 开发中最常用的空组件。

本文由作者按照 CC BY 4.0 进行授权