Repository navigation
Expand file tree
/
Copy pathview.dart
More file actions
958 lines (863 loc) · 36 KB
/
Copy pathview.dart
File metadata and controls
958 lines (863 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
// 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.
/// @docImport 'package:flutter/material.dart';
///
/// @docImport 'basic.dart';
library;
import 'dart:collection';
import 'dart:ui'
show FlutterView, SemanticsUpdate, ViewFocusDirection, ViewFocusEvent, ViewFocusState;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'binding.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'focus_traversal.dart';
import 'framework.dart';
import 'lookup_boundary.dart';
import 'media_query.dart';
// Whether [renderView], if there is one, renders into the view that [View] and
// [RawView] keep for [view], which is the one [debugViewWithMetricsOverrides]
// returns. That is the same object every time it is asked about the same view,
// so asking again here is the same as reading the field, which an initializer
// list assert cannot do. Only ever called from an assert.
bool _debugRenderViewRendersInto(RenderView? renderView, FlutterView view) {
assert(
renderView == null || identical(renderView.flutterView, debugViewWithMetricsOverrides(view)),
'A RenderView passed to View or RawView must render into the FlutterView '
'passed alongside it. Both are normalized by debugViewWithMetricsOverrides '
'and then compared by identity, so a view that merely compares == to the '
"RenderView's — a test double with an operator == of its own, say — is not "
'the same view for this purpose.',
);
return true;
}
/// Bootstraps a render tree that is rendered into the provided [FlutterView].
///
/// The content rendered into that view is determined by the provided [child].
/// Descendants within the same [LookupBoundary] can look up the view they are
/// rendered into via [View.of] and [View.maybeOf].
///
/// The provided [child] is wrapped in a [MediaQuery] constructed from the given
/// [view], a [FocusScope], and a [RawView] widget.
///
/// For most use cases, using [MediaQuery.of], or its associated "...Of" methods
/// are a more appropriate way of obtaining the information that a [FlutterView]
/// exposes. For example, using [MediaQuery.sizeOf] will expose the _logical_
/// device size ([MediaQueryData.size]) rather than the physical size
/// ([FlutterView.physicalSize]). Similarly, while [FlutterView.padding] conveys
/// the information from the operating system, the [MediaQueryData.padding]
/// attribute (obtained from [MediaQuery.paddingOf]) further adjusts this
/// information to be aware of the context of the widget; e.g. the [Scaffold]
/// widget adjusts the values for its various children.
///
/// Each [FlutterView] can be associated with at most one [View] or [RawView]
/// widget in the widget tree. Two or more [View] or [RawView] widgets
/// configured with the same [FlutterView] must never exist within the same
/// widget tree at the same time. This limitation is enforced by a
/// [GlobalObjectKey] that derives its identity from the [view] provided to this
/// widget.
///
/// Since the [View] widget bootstraps its own independent render tree using its
/// embedded [RawView], neither it nor any of its descendants will insert a
/// [RenderObject] into an existing render tree. Therefore, the [View] widget
/// can only be used in those parts of the widget tree where it is not required
/// to participate in the construction of the surrounding render tree. In other
/// words, the widget may only be used in a non-rendering zone of the widget
/// tree (see [WidgetsBinding] for a definition of rendering and non-rendering
/// zones).
///
/// In practical terms, the widget is typically used at the root of the widget
/// tree outside of any other [View] or [RawView] widget, as a child of a
/// [ViewCollection] widget, or in the [ViewAnchor.view] slot of a [ViewAnchor]
/// widget. It is not required to be a direct child, though, since other
/// non-[RenderObjectWidget]s (e.g. [InheritedWidget]s, [Builder]s, or
/// [StatefulWidget]s/[StatelessWidget]s that only produce
/// non-[RenderObjectWidget]s) are allowed to be present between those widgets
/// and the [View] widget.
///
/// See also:
///
/// * [RawView], the workhorse that [View] uses to create the render tree, but
/// without the [MediaQuery] and [FocusScope] that [View] adds.
/// * [Element.debugExpectsRenderObjectForSlot], which defines whether a [View]
/// widget is allowed in a given child slot.
class View extends StatefulWidget {
/// Create a [View] widget to bootstrap a render tree that is rendered into
/// the provided [FlutterView].
///
/// The content rendered into that [view] is determined by the given [child]
/// widget.
View({
super.key,
required FlutterView view,
@Deprecated(
'Do not use. '
'This parameter only exists to implement the deprecated RendererBinding.pipelineOwner property until it is removed. '
'This feature was deprecated after v3.10.0-12.0.pre.',
)
PipelineOwner? deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner,
@Deprecated(
'Do not use. '
'This parameter only exists to implement the deprecated RendererBinding.renderView property until it is removed. '
'This feature was deprecated after v3.10.0-12.0.pre.',
)
RenderView? deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView,
required this.child,
}) : view = kDebugMode ? debugViewWithMetricsOverrides(view) : view,
_deprecatedPipelineOwner = deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner,
_deprecatedRenderView = deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView,
assert(
(deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner == null) ==
(deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView == null),
),
assert(
_debugRenderViewRendersInto(deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView, view),
);
/// The [FlutterView] into which [child] is drawn.
///
/// This is the view passed to the constructor, normalized in debug mode with
/// [debugViewWithMetricsOverrides] so that it applies the
/// [debugViewMetricsOverrides] entry registered for its id.
final FlutterView view;
/// The widget below this widget in the tree, which will be drawn into the
/// [view].
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
final PipelineOwner? _deprecatedPipelineOwner;
final RenderView? _deprecatedRenderView;
/// Returns the [FlutterView] that the provided `context` will render into.
///
/// Returns null if the `context` is not associated with a [FlutterView].
///
/// The method creates a dependency on the `context`, which will be informed
/// when the identity of the [FlutterView] changes (i.e. the `context` is
/// moved to render into a different [FlutterView] then before). The context
/// will not be informed when the _properties_ on the [FlutterView] itself
/// change their values. To access the property values of a [FlutterView] it
/// is best practice to use [MediaQuery.maybeOf] instead, which will ensure
/// that the `context` is informed when the view properties change.
///
/// {@template flutter.widgets.View.debugViewMetricsOverrides}
/// In debug mode, a view that [PlatformDispatcher.instance] reports is used
/// through a wrapper that applies [debugViewMetricsOverrides], and this method
/// returns the wrapper. It is not identical to the view that
/// [PlatformDispatcher.instance] reports, and its
/// [FlutterView.platformDispatcher] is not identical to
/// [PlatformDispatcher.instance]. Compare views by [FlutterView.viewId]
/// instead.
/// {@endtemplate}
///
/// See also:
///
/// * [View.of], which throws instead of returning null if no [FlutterView]
/// is found.
static FlutterView? maybeOf(BuildContext context) {
return LookupBoundary.dependOnInheritedWidgetOfExactType<_ViewScope>(context)?.view;
}
/// Returns the [FlutterView] that the provided `context` will render into.
///
/// Throws if the `context` is not associated with a [FlutterView].
///
/// The method creates a dependency on the `context`, which will be informed
/// when the identity of the [FlutterView] changes (i.e. the `context` is
/// moved to render into a different [FlutterView] then before). The context
/// will not be informed when the _properties_ on the [FlutterView] itself
/// change their values. To access the property values of a [FlutterView]
/// prefer using the access methods on [MediaQuery], such as
/// [MediaQuery.sizeOf], which will ensure that the `context` is informed when
/// the view properties change.
///
/// {@macro flutter.widgets.View.debugViewMetricsOverrides}
///
/// See also:
///
/// * [View.maybeOf], which throws instead of returning null if no
/// [FlutterView] is found.
static FlutterView of(BuildContext context) {
final FlutterView? result = maybeOf(context);
assert(() {
if (result == null) {
final bool hiddenByBoundary =
LookupBoundary.debugIsHidingAncestorWidgetOfExactType<_ViewScope>(context);
final information = <DiagnosticsNode>[
if (hiddenByBoundary) ...<DiagnosticsNode>[
ErrorSummary(
'View.of() was called with a context that does not have access to a View widget.',
),
ErrorDescription(
'The context provided to View.of() does have a View widget ancestor, but it is hidden by a LookupBoundary.',
),
] else ...<DiagnosticsNode>[
ErrorSummary(
'View.of() was called with a context that does not contain a View widget.',
),
ErrorDescription(
'No View widget ancestor could be found starting from the context that was passed to View.of().',
),
],
ErrorDescription(
'The context used was:\n'
' $context',
),
ErrorHint('This usually means that the provided context is not associated with a View.'),
];
throw FlutterError.fromParts(information);
}
return true;
}());
return result!;
}
/// Returns the [PipelineOwner] parent to which a child [View] should attach
/// its [PipelineOwner] to.
///
/// If `context` has a [View] ancestor, it returns the [PipelineOwner]
/// responsible for managing the render tree of that view. If there is no
/// [View] ancestor, [RendererBinding.rootPipelineOwner] is returned instead.
static PipelineOwner pipelineOwnerOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<_PipelineOwnerScope>()?.pipelineOwner ??
RendererBinding.instance.rootPipelineOwner;
}
@override
State<View> createState() => _ViewState();
}
class _ViewState extends State<View> with WidgetsBindingObserver {
final FocusScopeNode _scopeNode = FocusScopeNode(debugLabel: kReleaseMode ? null : 'View Scope');
final FocusTraversalPolicy _policy = ReadingOrderTraversalPolicy();
bool _viewHasFocus = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_scopeNode.addListener(_scopeFocusChangeListener);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_scopeNode.removeListener(_scopeFocusChangeListener);
_scopeNode.dispose();
super.dispose();
}
void _scopeFocusChangeListener() {
if (_viewHasFocus == _scopeNode.hasFocus || !_scopeNode.hasFocus) {
return;
}
// Scope has gained focus, and it doesn't match the view focus, so inform
// the view so it knows to change its focus.
WidgetsBinding.instance.platformDispatcher.requestViewFocusChange(
direction: ViewFocusDirection.forward,
state: ViewFocusState.focused,
viewId: widget.view.viewId,
);
}
@override
void didChangeViewFocus(ViewFocusEvent event) {
_viewHasFocus = switch (event.state) {
ViewFocusState.focused => event.viewId == widget.view.viewId,
ViewFocusState.unfocused => false,
};
if (event.viewId != widget.view.viewId) {
return;
}
FocusNode nextFocus;
switch (event.state) {
case ViewFocusState.focused:
switch (event.direction) {
case ViewFocusDirection.forward:
nextFocus = _policy.findFirstFocus(_scopeNode, ignoreCurrentFocus: true) ?? _scopeNode;
case ViewFocusDirection.backward:
nextFocus = _policy.findLastFocus(_scopeNode, ignoreCurrentFocus: true);
case ViewFocusDirection.undefined:
nextFocus = _scopeNode;
}
nextFocus.requestFocus();
case ViewFocusState.unfocused:
// Focusing on the root scope node will "park" the focus, so that no
// descendant node will be given focus, and there's no widget that can
// receive keyboard events.
FocusManager.instance.rootScope.requestScopeFocus();
}
}
@override
Widget build(BuildContext context) {
return RawView(
view: widget.view,
deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: widget._deprecatedPipelineOwner,
deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: widget._deprecatedRenderView,
child: MediaQuery.fromView(
view: widget.view,
child: FocusTraversalGroup(
policy: _policy,
// Attach this view's focus subtree directly to the root scope rather
// than nesting it under an enclosing view's scope (which happens when
// a view is rendered inside another via a [ViewAnchor]). Each view is
// an independent focus root: nesting would otherwise make an ancestor
// view report hasFocus when a descendant view is focused, causing it
// to request native focus and pull its window forward.
parentNode: FocusManager.instance.rootScope,
child: FocusScope.withExternalFocusNode(
includeSemantics: false,
focusScopeNode: _scopeNode,
child: widget.child,
),
),
),
);
}
}
/// The lower level workhorse widget for [View] that bootstraps a render tree
/// for a view.
///
/// Typically, the [View] widget is used instead of a [RawView] widget to create
/// a view, since, in addition to creating a view, it also adds some useful
/// widgets, such as a [MediaQuery] and [FocusScope]. The [RawView] widget is
/// only used directly if it is not desirable to have these additional widgets
/// around the resulting widget tree. The [View] widget uses the [RawView]
/// widget internally to manage its [FlutterView].
///
/// This widget can be used at the root of the widget tree outside of any other
/// [View] or [RawView] widget, as a child to a [ViewCollection], or in the
/// [ViewAnchor.view] slot of a [ViewAnchor] widget. It is not required to be a
/// direct child of those widgets; other non-[RenderObjectWidget]s may appear in
/// between the two (such as an [InheritedWidget]).
///
/// Each [FlutterView] can be associated with at most one [View] or [RawView]
/// widget in the widget tree. Two or more [View] or [RawView] widgets
/// configured with the same [FlutterView] must never exist within the same
/// widget tree at the same time. This limitation is enforced by a
/// [GlobalObjectKey] that derives its identity from the [view] provided to this
/// widget.
///
/// Since the [RawView] widget bootstraps its own independent render tree,
/// neither it nor any of its descendants will insert a [RenderObject] into an
/// existing render tree. Therefore, the [RawView] widget can only be used in
/// those parts of the widget tree where it is not required to participate in
/// the construction of the surrounding render tree. In other words, the widget
/// may only be used in a non-rendering zone of the widget tree (see
/// [WidgetsBinding] for a definition of rendering and non-rendering zones).
///
/// To find the [FlutterView] associated with a [BuildContext], use [View.of] or
/// [View.maybeOf], even if the view was created using [RawView] instead of
/// [View].
///
/// See also:
///
/// * [View] for a higher level interface that also sets up a [MediaQuery] and
/// [FocusScope] for the view's widget tree.
class RawView extends StatelessWidget {
/// Creates a [RawView] widget.
RawView({
super.key,
required FlutterView view,
@Deprecated(
'Do not use. '
'This parameter only exists to implement the deprecated RendererBinding.pipelineOwner property until it is removed. '
'This feature was deprecated after v3.10.0-12.0.pre.',
)
PipelineOwner? deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner,
@Deprecated(
'Do not use. '
'This parameter only exists to implement the deprecated RendererBinding.renderView property until it is removed. '
'This feature was deprecated after v3.10.0-12.0.pre.',
)
RenderView? deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView,
required this.child,
}) : view = kDebugMode ? debugViewWithMetricsOverrides(view) : view,
_deprecatedPipelineOwner = deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner,
_deprecatedRenderView = deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView,
assert(
(deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner == null) ==
(deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView == null),
),
assert(
_debugRenderViewRendersInto(deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView, view),
);
/// The [FlutterView] into which [child] is drawn.
///
/// This is the view passed to the constructor, normalized in debug mode with
/// [debugViewWithMetricsOverrides] so that it applies the
/// [debugViewMetricsOverrides] entry registered for its id.
final FlutterView view;
/// The widget below this widget in the tree, which will be drawn into the
/// [view].
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
final PipelineOwner? _deprecatedPipelineOwner;
final RenderView? _deprecatedRenderView;
@override
Widget build(BuildContext context) {
return _RawViewInternal(
view: view,
deprecatedPipelineOwner: _deprecatedPipelineOwner,
deprecatedRenderView: _deprecatedRenderView,
builder: (BuildContext context, PipelineOwner owner) {
return _ViewScope(
view: view,
child: _PipelineOwnerScope(pipelineOwner: owner, child: child),
);
},
);
}
}
/// A builder for the content [Widget] of a [_RawViewInternal].
///
/// The widget returned by the builder defines the content that is drawn into
/// the [FlutterView] configured on the [_RawViewInternal].
///
/// The builder is given the [PipelineOwner] that the [_RawViewInternal] uses to
/// manage its render tree. Typical builder implementations make that pipeline
/// owner available as an attachment point for potential child views.
///
/// Used by [_RawViewInternal.builder].
typedef _RawViewContentBuilder = Widget Function(BuildContext context, PipelineOwner owner);
/// The workhorse behind the [RawView] widget that actually bootstraps a render
/// tree.
///
/// It instantiates the [RenderView] as the root of that render tree and adds it
/// to the [RendererBinding] via [RendererBinding.addRenderView]. It also owns
/// the [PipelineOwner] that manages this render tree and adds it as a child to
/// the surrounding parent [PipelineOwner] obtained with [View.pipelineOwnerOf].
/// This ensures that the render tree bootstrapped by this widget participates
/// properly in frame production and hit testing.
class _RawViewInternal extends RenderObjectWidget {
/// Create a [_RawViewInternal] widget to bootstrap a render tree that is
/// rendered into the provided [FlutterView].
///
/// The content rendered into that [view] is determined by the [Widget]
/// returned by [builder].
_RawViewInternal({
required this.view,
required PipelineOwner? deprecatedPipelineOwner,
required RenderView? deprecatedRenderView,
required this.builder,
}) : _deprecatedPipelineOwner = deprecatedPipelineOwner,
_deprecatedRenderView = deprecatedRenderView,
assert(deprecatedRenderView == null || deprecatedRenderView.flutterView == view),
// TODO(goderbauer): Replace this with GlobalObjectKey(view) when the deprecated properties are removed.
super(key: _DeprecatedRawViewKey(view, deprecatedPipelineOwner, deprecatedRenderView));
/// The [FlutterView] into which the [Widget] returned by [builder] is drawn.
final FlutterView view;
/// Determines the content [Widget] that is drawn into the [view].
///
/// The [builder] is given the [PipelineOwner] responsible for the render tree
/// bootstrapped by this widget and typically makes it available as an
/// attachment point for potential child views.
final _RawViewContentBuilder builder;
final PipelineOwner? _deprecatedPipelineOwner;
final RenderView? _deprecatedRenderView;
@override
RenderObjectElement createElement() => _RawViewElement(this);
@override
RenderObject createRenderObject(BuildContext context) {
return _deprecatedRenderView ?? RenderView(view: view);
}
// No need to implement updateRenderObject: RawView uses the view as a
// GlobalKey, so we never need to update the RenderObject with a new view.
}
class _RawViewElement extends RenderTreeRootElement {
_RawViewElement(super.widget);
late final PipelineOwner _pipelineOwner = PipelineOwner(
onSemanticsOwnerCreated: _handleSemanticsOwnerCreated,
onSemanticsUpdate: _handleSemanticsUpdate,
onSemanticsOwnerDisposed: _handleSemanticsOwnerDisposed,
);
PipelineOwner get _effectivePipelineOwner =>
(widget as _RawViewInternal)._deprecatedPipelineOwner ?? _pipelineOwner;
void _handleSemanticsOwnerCreated() {
(_effectivePipelineOwner.rootNode as RenderView?)?.scheduleInitialSemantics();
}
void _handleSemanticsOwnerDisposed() {
(_effectivePipelineOwner.rootNode as RenderView?)?.clearSemantics();
}
void _handleSemanticsUpdate(SemanticsUpdate update) {
(widget as _RawViewInternal).view.updateSemantics(update);
}
@override
RenderView get renderObject => super.renderObject as RenderView;
Element? _child;
void _updateChild() {
try {
final Widget child = (widget as _RawViewInternal).builder(this, _effectivePipelineOwner);
_child = updateChild(_child, child, null);
} catch (e, stack) {
final details = FlutterErrorDetails(
exception: e,
stack: stack,
library: 'widgets library',
context: ErrorDescription('building $this'),
informationCollector: !kDebugMode
? null
: () => <DiagnosticsNode>[DiagnosticsDebugCreator(DebugCreator(this))],
);
FlutterError.reportError(details);
final Widget error = ErrorWidget.builder(details);
_child = updateChild(null, error, slot);
}
}
@override
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot);
assert(_effectivePipelineOwner.rootNode == null);
_effectivePipelineOwner.rootNode = renderObject;
_attachView();
_updateChild();
renderObject.prepareInitialFrame();
if (_effectivePipelineOwner.semanticsOwner != null) {
renderObject.scheduleInitialSemantics();
}
}
PipelineOwner? _parentPipelineOwner; // Is null if view is currently not attached.
void _attachView([PipelineOwner? parentPipelineOwner]) {
assert(_parentPipelineOwner == null);
parentPipelineOwner ??= View.pipelineOwnerOf(this);
parentPipelineOwner.adoptChild(_effectivePipelineOwner);
RendererBinding.instance.addRenderView(renderObject);
_parentPipelineOwner = parentPipelineOwner;
}
void _detachView() {
final PipelineOwner? parentPipelineOwner = _parentPipelineOwner;
if (parentPipelineOwner != null) {
RendererBinding.instance.removeRenderView(renderObject);
parentPipelineOwner.dropChild(_effectivePipelineOwner);
_parentPipelineOwner = null;
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_parentPipelineOwner == null) {
return;
}
final PipelineOwner newParentPipelineOwner = View.pipelineOwnerOf(this);
if (newParentPipelineOwner != _parentPipelineOwner) {
_detachView();
_attachView(newParentPipelineOwner);
}
}
@override
void performRebuild() {
super.performRebuild();
_updateChild();
}
@override
void activate() {
super.activate();
assert(_effectivePipelineOwner.rootNode == null);
_effectivePipelineOwner.rootNode = renderObject;
_attachView();
}
@override
void deactivate() {
_detachView();
assert(_effectivePipelineOwner.rootNode == renderObject);
_effectivePipelineOwner.rootNode = null; // To satisfy the assert in the super class.
super.deactivate();
}
@override
void update(_RawViewInternal newWidget) {
super.update(newWidget);
_updateChild();
}
@override
void visitChildren(ElementVisitor visitor) {
if (_child != null) {
visitor(_child!);
}
}
@override
void forgetChild(Element child) {
assert(child == _child);
_child = null;
super.forgetChild(child);
}
@override
void insertRenderObjectChild(RenderBox child, Object? slot) {
assert(slot == null);
assert(renderObject.debugValidateChild(child));
renderObject.child = child;
}
@override
void moveRenderObjectChild(RenderObject child, Object? oldSlot, Object? newSlot) {
assert(false);
}
@override
void removeRenderObjectChild(RenderObject child, Object? slot) {
assert(slot == null);
assert(renderObject.child == child);
renderObject.child = null;
}
@override
void unmount() {
if (_effectivePipelineOwner != (widget as _RawViewInternal)._deprecatedPipelineOwner) {
_effectivePipelineOwner.dispose();
}
super.unmount();
}
}
class _ViewScope extends InheritedWidget {
const _ViewScope({required this.view, required super.child});
final FlutterView view;
@override
bool updateShouldNotify(_ViewScope oldWidget) => view != oldWidget.view;
}
class _PipelineOwnerScope extends InheritedWidget {
const _PipelineOwnerScope({required this.pipelineOwner, required super.child});
final PipelineOwner pipelineOwner;
@override
bool updateShouldNotify(_PipelineOwnerScope oldWidget) =>
pipelineOwner != oldWidget.pipelineOwner;
}
class _MultiChildComponentWidget extends Widget {
const _MultiChildComponentWidget({super.key, this._views = const <Widget>[], this._child});
// It is up to the subclasses to make the relevant properties public.
final List<Widget> _views;
final Widget? _child;
@override
Element createElement() => _MultiChildComponentElement(this);
}
/// A collection of sibling [View]s.
///
/// This widget can only be used in places were a [View] widget is allowed, i.e.
/// in a non-rendering zone of the widget tree. In practical terms, it can be
/// used at the root of the widget tree outside of any [View] widget, as a child
/// to a another [ViewCollection], or in the [ViewAnchor.view] slot of a
/// [ViewAnchor] widget. It is not required to be a direct child of those
/// widgets; other non-[RenderObjectWidget]s may appear in between the two (such
/// as an [InheritedWidget]).
///
/// Similarly, the [views] children of this widget must be [View]s, but they
/// may be wrapped in additional non-[RenderObjectWidget]s (e.g.
/// [InheritedWidget]s).
///
/// See also:
///
/// * [WidgetsBinding] for an explanation of rendering and non-rendering zones.
class ViewCollection extends _MultiChildComponentWidget {
/// Creates a [ViewCollection] widget.
const ViewCollection({super.key, required super.views});
/// The [View] descendants of this widget.
///
/// The [View]s may be wrapped in other non-[RenderObjectWidget]s (e.g.
/// [InheritedWidget]s). However, no [RenderObjectWidget] is allowed to appear
/// between the [ViewCollection] and the next [View] widget.
List<Widget> get views => _views;
}
/// Decorates a [child] widget with a side [View].
///
/// This widget must have a [View] ancestor, into which the [child] widget
/// is rendered.
///
/// Typically, a [View] or [ViewCollection] widget is used in the [view] slot to
/// define the content of the side view(s). Those widgets may be wrapped in
/// other non-[RenderObjectWidget]s (e.g. [InheritedWidget]s). However, no
/// [RenderObjectWidget] is allowed to appear between the [ViewAnchor] and the
/// next [View] widget in the [view] slot. The widgets in the [view] slot have
/// access to all [InheritedWidget]s above the [ViewAnchor] in the tree.
///
/// In technical terms, the [ViewAnchor] can only be used in a rendering zone of
/// the widget tree and the [view] slot marks the start of a new non-rendering
/// zone (see [WidgetsBinding] for a definition of these zones). Typically,
/// it is occupied by a [View] widget, which will start a new rendering zone.
///
/// {@template flutter.widgets.ViewAnchor}
/// An example use case for this widget is a tooltip for a button. The tooltip
/// should be able to extend beyond the bounds of the main view. For this, the
/// tooltip can be implemented as a separate [View], which is anchored to the
/// button in the main view by wrapping that button with a [ViewAnchor]. In this
/// example, the [view] slot is configured with the tooltip [View] and the
/// [child] is the button widget rendered into the surrounding view.
/// {@endtemplate}
class ViewAnchor extends StatelessWidget {
/// Creates a [ViewAnchor] widget.
const ViewAnchor({super.key, this.view, required this.child});
/// The widget that defines the view anchored to this widget.
///
/// Typically, a [View] or [ViewCollection] widget is used, which may be
/// wrapped in other non-[RenderObjectWidget]s (e.g. [InheritedWidget]s).
///
/// {@macro flutter.widgets.ViewAnchor}
final Widget? view;
/// The widget below this widget in the tree.
///
/// It is rendered into the surrounding view, not in the view defined by
/// [view].
///
/// {@macro flutter.widgets.ViewAnchor}
final Widget child;
@override
Widget build(BuildContext context) {
return _MultiChildComponentWidget(
views: <Widget>[if (view != null) LookupBoundary(child: view!)],
child: child,
);
}
}
class _MultiChildComponentElement extends Element {
_MultiChildComponentElement(super.widget);
List<Element> _viewElements = <Element>[];
final Set<Element> _forgottenViewElements = HashSet<Element>();
Element? _childElement;
bool _debugAssertChildren() {
final typedWidget = widget as _MultiChildComponentWidget;
// Each view widget must have a corresponding element.
assert(_viewElements.length == typedWidget._views.length);
// Iff there is a child widget, it must have a corresponding element.
assert((_childElement == null) == (typedWidget._child == null));
// The child element is not also a view element.
assert(!_viewElements.contains(_childElement));
return true;
}
@override
void attachRenderObject(Object? newSlot) {
super.attachRenderObject(newSlot);
assert(_debugCheckMustAttachRenderObject(newSlot));
}
@override
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot);
assert(_debugCheckMustAttachRenderObject(newSlot));
assert(_viewElements.isEmpty);
assert(_childElement == null);
rebuild();
assert(_debugAssertChildren());
}
@override
void updateSlot(Object? newSlot) {
super.updateSlot(newSlot);
assert(_debugCheckMustAttachRenderObject(newSlot));
}
bool _debugCheckMustAttachRenderObject(Object? slot) {
// Check only applies in the ViewCollection configuration.
if (!kDebugMode || (widget as _MultiChildComponentWidget)._child != null) {
return true;
}
var hasAncestorRenderObjectElement = false;
var ancestorWantsRenderObject = true;
visitAncestorElements((Element ancestor) {
if (!ancestor.debugExpectsRenderObjectForSlot(slot)) {
ancestorWantsRenderObject = false;
return false;
}
if (ancestor is RenderObjectElement) {
hasAncestorRenderObjectElement = true;
return false;
}
return true;
});
if (hasAncestorRenderObjectElement && ancestorWantsRenderObject) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'The Element for ${toStringShort()} cannot be inserted into slot "$slot" of its ancestor. ',
),
ErrorDescription(
'The ownership chain for the Element in question was:\n ${debugGetCreatorChain(10)}',
),
ErrorDescription(
'This Element allows the creation of multiple independent render trees, which cannot '
'be attached to an ancestor in an existing render tree. However, an ancestor RenderObject '
'is expecting that a child will be attached.',
),
ErrorHint(
'Try moving the subtree that contains the ${toStringShort()} widget into the '
'view property of a ViewAnchor widget or to the root of the widget tree, where '
'it is not expected to attach its RenderObject to its ancestor.',
),
]),
),
);
}
return true;
}
@override
void update(_MultiChildComponentWidget newWidget) {
// Cannot switch from ViewAnchor config to ViewCollection config.
assert((newWidget._child == null) == ((widget as _MultiChildComponentWidget)._child == null));
super.update(newWidget);
rebuild(force: true);
assert(_debugAssertChildren());
}
static const Object _viewSlot = Object();
@override
bool debugExpectsRenderObjectForSlot(Object? slot) => slot != _viewSlot;
@override
void performRebuild() {
final typedWidget = widget as _MultiChildComponentWidget;
_childElement = updateChild(_childElement, typedWidget._child, slot);
final List<Widget> views = typedWidget._views;
_viewElements = updateChildren(
_viewElements,
views,
forgottenChildren: _forgottenViewElements,
slots: List<Object>.generate(views.length, (_) => _viewSlot),
);
_forgottenViewElements.clear();
super.performRebuild(); // clears the dirty flag
assert(_debugAssertChildren());
}
@override
void forgetChild(Element child) {
if (child == _childElement) {
_childElement = null;
} else {
assert(_viewElements.contains(child));
assert(!_forgottenViewElements.contains(child));
_forgottenViewElements.add(child);
}
super.forgetChild(child);
}
@override
void visitChildren(ElementVisitor visitor) {
if (_childElement != null) {
visitor(_childElement!);
}
for (final Element child in _viewElements) {
if (!_forgottenViewElements.contains(child)) {
visitor(child);
}
}
}
@override
bool get debugDoingBuild => false; // This element does not have a concept of "building".
@override
Element? get renderObjectAttachingChild => _childElement;
@override
List<DiagnosticsNode> debugDescribeChildren() {
return <DiagnosticsNode>[
?_childElement?.toDiagnosticsNode(),
for (int i = 0; i < _viewElements.length; i++)
_viewElements[i].toDiagnosticsNode(
name: 'view ${i + 1}',
style: DiagnosticsTreeStyle.offstage,
),
];
}
}
// A special [GlobalKey] to support passing the deprecated
// [RendererBinding.renderView] and [RendererBinding.pipelineOwner] to the
// [_RawView]. Will be removed when those deprecated properties are removed.
@optionalTypeArgs
class _DeprecatedRawViewKey<T extends State<StatefulWidget>> extends GlobalKey<T> {
const _DeprecatedRawViewKey(this.view, this.owner, this.renderView) : super.constructor();
final FlutterView view;
final PipelineOwner? owner;
final RenderView? renderView;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is _DeprecatedRawViewKey<T> &&
identical(other.view, view) &&
identical(other.owner, owner) &&
identical(other.renderView, renderView);
}
@override
int get hashCode => Object.hash(view, owner, renderView);
@override
String toString() => '[_DeprecatedRawViewKey ${describeIdentity(view)}]';
}