带有颜色优化的容器
概述
#框架中新增了一个 ColoredBox
组件,并且 Container
组件已优化,在用户指定 color
而非 decoration
时会使用它。
背景
#使用 Container
组件的方式如下
dart
return Container(color: Colors.red);
此前,这段代码会导致一个组件层级,其中使用 BoxDecoration
来实际绘制背景颜色。BoxDecoration
组件除了绘制背景颜色之外,还涵盖了许多其他情况,并且不如新的 ColoredBox
组件高效,后者仅用于绘制背景颜色。
以前,在组件树中想要根据容器颜色进行断言的组件测试,必须找到 BoxDecoration
才能实际获取容器的颜色。现在,它们可以直接检查 Container
本身的 color
属性,除非 BoxDecoration
被明确作为 decoration
属性提供。同时为 Container
提供 color
和 decoration
仍然是一个错误。
迁移指南
#断言 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);
// Or, a test may have specifically looked for the BoxDecoration, e.g.:
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);
// If your test needed to work directly with the BoxDecoration, it should
// instead look for the ColoredBox, e.g.:
expect(find.byType(BoxDecoration), findsNothing);
expect(find.byType(ColoredBox), findsOneWidget);
});
时间线
#引入版本: 1.15.4
稳定版本: 1.17
参考资料
#API 文档
相关问题
相关 PR