帶顏色最佳化的 Container
概述
#框架中新增了一個 ColoredBox widget,並且 Container widget 得到了最佳化,當用戶指定 color 而非 decoration 時,它會使用 ColoredBox。
背景
#以下是使用 Container widget 的常見方式:
dart
return Container(color: Colors.red);以前,此程式碼會生成一個 widget 層級,該層級使用 BoxDecoration 來實際繪製背景顏色。BoxDecoration widget 涵蓋了除繪製背景顏色之外的許多情況,並且不如新的 ColoredBox widget 高效,後者僅繪製背景顏色。
以前,希望基於 widget 樹中 container 顏色的 widget 測試,必須找到 BoxDecoration 才能實際獲取 container 的顏色。現在,它們能夠直接檢查 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