build_owner.0.dart 1.74 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
/// Flutter code sample for [BuildOwner].
6

7
import 'package:flutter/material.dart';
8 9 10 11
import 'package:flutter/rendering.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
  final Size size = measureWidget(const SizedBox(width: 640, height: 480));

  // Just displays the size calculated above.
  runApp(
    WidgetsApp(
      title: 'BuildOwner Sample',
      color: const Color(0xff000000),
      builder: (BuildContext context, Widget? child) {
        return Scaffold(
          body: Center(
            child: Text(size.toString()),
          ),
        );
      },
    ),
  );
28 29 30 31 32 33
}

Size measureWidget(Widget widget) {
  final PipelineOwner pipelineOwner = PipelineOwner();
  final MeasurementView rootView = pipelineOwner.rootNode = MeasurementView();
  final BuildOwner buildOwner = BuildOwner(focusManager: FocusManager());
34
  final RenderObjectToWidgetElement<RenderBox> element = RenderObjectToWidgetAdapter<RenderBox>(
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    container: rootView,
    debugShortDescription: '[root]',
    child: widget,
  ).attachToRenderTree(buildOwner);
  try {
    rootView.scheduleInitialLayout();
    pipelineOwner.flushLayout();
    return rootView.size;
  } finally {
    // Clean up.
    element.update(RenderObjectToWidgetAdapter<RenderBox>(container: rootView));
    buildOwner.finalizeTree();
  }
}

50
class MeasurementView extends RenderBox with RenderObjectWithChildMixin<RenderBox> {
51 52 53 54 55 56 57 58 59 60
  @override
  void performLayout() {
    assert(child != null);
    child!.layout(const BoxConstraints(), parentUsesSize: true);
    size = child!.size;
  }

  @override
  void debugAssertDoesMeetConstraints() => true;
}