Visitar URL original
Colored box and container optimization by dnfield · Pull Request #50979 · flutter/flutter · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions packages/flutter/lib/src/widgets/basic.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7071,3 +7071,57 @@ class _StatefulBuilderState extends State<StatefulBuilder> {
@override
Widget build(BuildContext context) => widget.builder(context, setState);
}

/// A widget that paints its area with a specified [Color] and then draws its
/// child on top of that color.
class ColoredBox extends SingleChildRenderObjectWidget {
/// Creates a widget that paints its area with the specified [Color].
///
/// The [color] parameter must not be null.
const ColoredBox({@required this.color, Widget child, Key key})
: assert(color != null),
super(key: key, child: child);

/// The color to paint the background area with.
final Color color;

@override
_RenderColoredBox createRenderObject(BuildContext context) {
return _RenderColoredBox(color: color);
}

@override
void updateRenderObject(BuildContext context, _RenderColoredBox renderObject) {
renderObject.color = color;
}
}

class _RenderColoredBox extends RenderProxyBoxWithHitTestBehavior {
_RenderColoredBox({@required Color color})
: _color = color,
super(behavior: HitTestBehavior.opaque);

/// The fill color for this render object.
///
/// This parameter must not be null.
Color get color => _color;
Color _color;
set color(Color value) {
assert(value != null);
if (value == _color) {
return;
}
_color = value;
markNeedsPaint();
}

@override
void paint(PaintingContext context, Offset offset) {
if (size > Size.zero) {
context.canvas.drawRect(offset & size, Paint()..color = color);
}
if (child != null) {
context.paintChild(child, offset);
}
}
}
28 changes: 16 additions & 12 deletions packages/flutter/lib/src/widgets/container.dart
Original file line number Diff line number Diff line change
Expand Up @@ -294,17 +294,16 @@ class Container extends StatelessWidget {
///
/// The `height` and `width` values include the padding.
///
/// The `color` argument is a shorthand for `decoration: new
/// BoxDecoration(color: color)`, which means you cannot supply both a `color`
/// and a `decoration` argument. If you want to have both a `color` and a
/// `decoration`, you can pass the color as the `color` argument to the
/// `BoxDecoration`.
/// The `color` and `decoration` arguments cannot both be supplied, since
/// it would potentially result in the decoration drawing over the background
/// color. To supply a decoration with a color, use `decoration:
/// BoxDecoration(color: color)`.
Container({
Key key,
this.alignment,
this.padding,
Color color,
Decoration decoration,
this.color,
this.decoration,
this.foregroundDecoration,
double width,
double height,
Expand All @@ -320,9 +319,8 @@ class Container extends StatelessWidget {
assert(clipBehavior != null),
assert(color == null || decoration == null,
'Cannot provide both a color and a decoration\n'
'The color argument is just a shorthand for "decoration: new BoxDecoration(color: color)".'
'To provide both, use "decoration: new BoxDecoration(color: color)".'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Don't need the new here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

),
decoration = decoration ?? (color != null ? BoxDecoration(color: color) : null),
constraints =
(width != null || height != null)
? constraints?.tighten(width: width, height: height)
Expand Down Expand Up @@ -363,11 +361,14 @@ class Container extends StatelessWidget {
/// see [Decoration.padding].
final EdgeInsetsGeometry padding;

/// The color to paint behind the [child].
///
/// This will paint behind the [decoration], if any.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update this comment since you can no longer have both?

final Color color;

/// The decoration to paint behind the [child].
///
/// A shorthand for specifying just a solid color is available in the
/// constructor: set the `color` argument instead of the `decoration`
/// argument.
/// Use the [color] property to specify a simple solid color.
///
/// The [child] is not clipped to the decoration. To clip a child to the shape
/// of a particular [ShapeDecoration], consider using a [ClipPath] widget.
Expand Down Expand Up @@ -423,6 +424,9 @@ class Container extends StatelessWidget {
if (effectivePadding != null)
current = Padding(padding: effectivePadding, child: current);

if (color != null)
current = ColoredBox(color: color, child: current);

if (decoration != null)
current = DecoratedBox(decoration: decoration, child: current);

Expand Down
2 changes: 1 addition & 1 deletion packages/flutter/test/material/banner_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ void main() {
);

final Container container = _getContainerFromBanner(tester);
expect(container.decoration, const BoxDecoration(color: color));
expect(container.color, color);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here and elsewhere: A simple container with a color no longer creates a BoxDecoration. This is the break.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When making a change like this, are there metrics for before and after? I'm curious about rendering speed (which I would expect to improve) and app size (which I would expect to increase slightly).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recorded but have lost some performance gains in various timeline summary benchmarks we run. The results are not earth shaking, but it is a bump in performance for frame times - we use a lot of containers in the framework, and containers are a very common widget to use.

On the Flutter Gallery, building with this patch is not enough to meaningfully impact the app.so/app.dill sizes when building the release AOT bundle. They measure using the same number of blocks on my local disk with and without this patch.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I generate the heapsnapshots for each, the one with the ColoredBox takes slightly more space, indicating that the colored box is getting properly shaken out of both types.

The added classes are pretty tiny though :)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the info. Reading through this, I was suddenly curious what the life cycle of an SDK optimization like this was.

});

testWidgets('Custom content TextStyle respected', (WidgetTester tester) async {
Expand Down
8 changes: 4 additions & 4 deletions packages/flutter/test/material/banner_theme_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ void main() {

final Container container = _getContainerFromBanner(tester);
final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText);
expect(container.decoration, const BoxDecoration(color: Color(0xffffffff)));
expect(container.color, const Color(0xffffffff));
// Default value for ThemeData.typography is Typography.material2014()
expect(content.text.style, Typography.material2014().englishLike.bodyText2.merge(Typography.material2014().black.bodyText2));
});
Expand All @@ -92,7 +92,7 @@ void main() {

final Container container = _getContainerFromBanner(tester);
final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText);
expect(container.decoration, BoxDecoration(color: bannerTheme.backgroundColor));
expect(container.color, bannerTheme.backgroundColor);
expect(content.text.style, bannerTheme.contentTextStyle);

final Offset contentTopLeft = tester.getTopLeft(_textFinder(contentText));
Expand Down Expand Up @@ -131,7 +131,7 @@ void main() {

final Container container = _getContainerFromBanner(tester);
final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText);
expect(container.decoration, const BoxDecoration(color: backgroundColor));
expect(container.color, backgroundColor);
expect(content.text.style, textStyle);

final Offset contentTopLeft = tester.getTopLeft(_textFinder(contentText));
Expand Down Expand Up @@ -161,7 +161,7 @@ void main() {
));

final Container container = _getContainerFromBanner(tester);
expect(container.decoration, BoxDecoration(color: colorScheme.surface));
expect(container.color, colorScheme.surface);
});
}

Expand Down
8 changes: 2 additions & 6 deletions packages/flutter/test/material/drawer_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,7 @@ void main() {
scaffoldKey.currentState.openDrawer();
await tester.pumpAndSettle();

BoxDecoration decoration = getScrim().decoration as BoxDecoration;
expect(decoration.color, Colors.black54);
expect(decoration.shape, BoxShape.rectangle);
expect(getScrim().color, Colors.black54);

await tester.tap(find.byType(Drawer));
await tester.pumpAndSettle();
Expand All @@ -162,9 +160,7 @@ void main() {
scaffoldKey.currentState.openDrawer();
await tester.pumpAndSettle();

decoration = getScrim().decoration as BoxDecoration;
expect(decoration.color, const Color(0xFF323232));
expect(decoration.shape, BoxShape.rectangle);
expect(getScrim().color, const Color(0xFF323232));

await tester.tap(find.byType(Drawer));
await tester.pumpAndSettle();
Expand Down
8 changes: 3 additions & 5 deletions packages/flutter/test/material/inherited_theme_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ void main() {
}

Color containerColor() {
final BoxDecoration decoration = tester.widget<Container>(find.byKey(primaryContainerKey)).decoration as BoxDecoration;
return decoration.color;
return tester.widget<Container>(find.byKey(primaryContainerKey)).color;
}

await tester.pumpWidget(buildFrame());
Expand Down Expand Up @@ -225,10 +224,9 @@ void main() {
}

Color bannerColor() {
final BoxDecoration decoration = tester.widget<Container>(
return tester.widget<Container>(
find.descendant(of: find.byType(MaterialBanner), matching: find.byType(Container)).first,
).decoration as BoxDecoration;
return decoration.color;
).color;
}

TextStyle getTextStyle(String text) {
Expand Down
88 changes: 88 additions & 0 deletions packages/flutter/test/widgets/basic_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/rendering.dart';
import 'package:mockito/mockito.dart';

void main() {
group('PhysicalShape', () {
Expand Down Expand Up @@ -278,6 +279,90 @@ void main() {
equals('UnconstrainedBox(alignment: topRight, constrainedAxis: horizontal, textDirection: rtl)'),
);
});

group('ColoredBox', () {
_MockCanvas mockCanvas;
_MockPaintingContext mockContext;
const Color colorToPaint = Color(0xFFABCDEF);

setUp(() {
mockContext = _MockPaintingContext();
mockCanvas = _MockCanvas();
when(mockContext.canvas).thenReturn(mockCanvas);
});

testWidgets('ColoredBox - no size, no child', (WidgetTester tester) async {
await tester.pumpWidget(Flex(
direction: Axis.horizontal,
textDirection: TextDirection.ltr,
children: const <Widget>[
SizedBox.shrink(
child: ColoredBox(color: colorToPaint),
),
],
));
expect(find.byType(ColoredBox), findsOneWidget);
final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox));

renderColoredBox.paint(mockContext, Offset.zero);

verifyNever(mockCanvas.drawRect(any, any));
verifyNever(mockContext.paintChild(any, any));
});

testWidgets('ColoredBox - no size, child', (WidgetTester tester) async {
const ValueKey<int> key = ValueKey<int>(0);
const Widget child = SizedBox.expand(key: key);
await tester.pumpWidget(Flex(
direction: Axis.horizontal,
textDirection: TextDirection.ltr,
children: const <Widget>[
SizedBox.shrink(
child: ColoredBox(color: colorToPaint, child: child),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the child = SizedBox.expand(key: key) also have 0 size? My first reaction is that a parent ColoredBox is at least the size of its child, so a 0-sized parent ColoredBox infers a 0-sized child.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have to break out of the constraints of the tester to make any of this work - we could also use a child instead of a parent to do it, but we need to make sure we're in a context where we won't just take up the full available space anwyya (e.g. using a flexible).

),
],
));
expect(find.byType(ColoredBox), findsOneWidget);
final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox));
final RenderObject renderSizedBox = tester.renderObject(find.byKey(key));

renderColoredBox.paint(mockContext, Offset.zero);

verifyNever(mockCanvas.drawRect(any, any));
verify(mockContext.paintChild(renderSizedBox, Offset.zero)).called(1);
});

testWidgets('ColoredBox - size, no child', (WidgetTester tester) async {
await tester.pumpWidget(const ColoredBox(color: colorToPaint));
expect(find.byType(ColoredBox), findsOneWidget);
final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox));

renderColoredBox.paint(mockContext, Offset.zero);

final List<dynamic> drawRect = verify(mockCanvas.drawRect(captureAny, captureAny)).captured;
expect(drawRect.length, 2);
expect(drawRect[0], const Rect.fromLTWH(0, 0, 800, 600));
expect(drawRect[1].color, colorToPaint);
verifyNever(mockContext.paintChild(any, any));
});

testWidgets('ColoredBox - size, child', (WidgetTester tester) async {
const ValueKey<int> key = ValueKey<int>(0);
const Widget child = SizedBox.expand(key: key);
await tester.pumpWidget(const ColoredBox(color: colorToPaint, child: child));
expect(find.byType(ColoredBox), findsOneWidget);
final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox));
final RenderObject renderSizedBox = tester.renderObject(find.byKey(key));

renderColoredBox.paint(mockContext, Offset.zero);

final List<dynamic> drawRect = verify(mockCanvas.drawRect(captureAny, captureAny)).captured;
expect(drawRect.length, 2);
expect(drawRect[0], const Rect.fromLTWH(0, 0, 800, 600));
expect(drawRect[1].color, colorToPaint);
verify(mockContext.paintChild(renderSizedBox, Offset.zero)).called(1);
});
});
}

HitsRenderBox hits(RenderBox renderBox) => HitsRenderBox(renderBox);
Expand Down Expand Up @@ -319,3 +404,6 @@ class DoesNotHitRenderBox extends Matcher {
).isEmpty;
}
}

class _MockPaintingContext extends Mock implements PaintingContext {}
class _MockCanvas extends Mock implements Canvas {}
Loading