带颜色的容器优化
摘要
#框架中添加了一个新的 ColoredBox
组件,并且 Container
组件进行了优化,如果用户指定了 color
而不是 decoration
,则会使用 ColoredBox
。
背景
#如下使用 Container
组件非常常见:
dart
return Container(color: Colors.red);
以前,这段代码生成的组件层次结构使用 BoxDecoration
来实际绘制背景颜色。BoxDecoration
组件涵盖了除绘制背景颜色之外的许多情况,并且不如新的 ColoredBox
组件高效,后者只绘制背景颜色。
以前,想要根据组件树中容器的颜色进行断言的组件测试必须找到 BoxDecoration
来实际获取容器的颜色。现在,除非显式提供 BoxDecoration
作为 decoration
属性,否则可以直接检查 Container
本身的 color
属性。同时提供 color
和 decoration
给 Container
仍然是一个错误。
迁移指南
#需要修改断言 Container
颜色或预期它创建 BoxDecoration
的测试。
迁移前的代码:
dart
testWidgets('Container color', (WidgetTester tester) async {
await tester.pumpWidget(Container(color: Colors.red));
final Container container = tester.widgetList<Container>().first;
expect(container.decoration.color, Colors.red);
// 或者,测试可能专门查找 BoxDecoration,例如:
expect(find.byType(BoxDecoration), findsOneWidget);
});
迁移后的代码:
dart
testWidgets('Container color', (WidgetTester tester) async {
await tester.pumpWidget(Container(color: Colors.red));
final Container container = tester.widgetList<Container>().first;
expect(container.color, Colors.red);
// 如果您的测试需要直接使用 BoxDecoration,则应改为查找 ColoredBox,例如:
expect(find.byType(BoxDecoration), findsNothing);
expect(find.byType(ColoredBox), findsOneWidget);
});
时间线
#包含的版本:1.15.4
稳定版本:1.17
参考
#API 文档:
相关问题:
相关 PR:
除非另有说明,否则本网站上的文档反映的是 Flutter 的最新稳定版本。页面最后更新于 2025-01-30。 查看源代码 或 报告问题。