1// Copyright 2014 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5import 'package:flutter/material.dart';
6import 'package:flutter/rendering.dart';
7
8/// Flutter code sample for [BuildOwner].
9
10void main() {
11 WidgetsFlutterBinding.ensureInitialized();
12 final Size size = measureWidget(const SizedBox(width: 640, height: 480));
13
14 // Just displays the size calculated above.
15 runApp(
16 WidgetsApp(
17 title: 'BuildOwner Sample',
18 color: const Color(0xff000000),
19 builder: (BuildContext context, Widget? child) {
20 return Scaffold(
21 body: Center(
22 child: Text(size.toString()),
23 ),
24 );
25 },
26 ),
27 );
28}
29
30Size measureWidget(Widget widget) {
31 final PipelineOwner pipelineOwner = PipelineOwner();
32 final MeasurementView rootView = pipelineOwner.rootNode = MeasurementView();
33 final BuildOwner buildOwner = BuildOwner(focusManager: FocusManager());
34 final RenderObjectToWidgetElement<RenderBox> element = RenderObjectToWidgetAdapter<RenderBox>(
35 container: rootView,
36 debugShortDescription: '[root]',
37 child: widget,
38 ).attachToRenderTree(buildOwner);
39 try {
40 rootView.scheduleInitialLayout();
41 pipelineOwner.flushLayout();
42 return rootView.size;
43 } finally {
44 // Clean up.
45 element.update(RenderObjectToWidgetAdapter<RenderBox>(container: rootView));
46 buildOwner.finalizeTree();
47 }
48}
49
50class MeasurementView extends RenderBox with RenderObjectWithChildMixin<RenderBox> {
51 @override
52 void performLayout() {
53 assert(child != null);
54 child!.layout(const BoxConstraints(), parentUsesSize: true);
55 size = child!.size;
56 }
57
58 @override
59 void debugAssertDoesMeetConstraints() => true;
60}
61

Provided by KDAB

Privacy Policy
Learn more about Flutter for embedded and desktop on industrialflutter.com