-
Notifications
You must be signed in to change notification settings - Fork 30.1k
Expand file tree
/
Copy pathbinding.dart
More file actions
2146 lines (2006 loc) · 78.6 KB
/
binding.dart
File metadata and controls
2146 lines (2006 loc) · 78.6 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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 'dart:ui';
/// @docImport 'package:flutter/animation.dart';
/// @docImport 'package:flutter/material.dart';
/// @docImport 'package:flutter_test/flutter_test.dart';
///
/// @docImport 'adapter.dart';
/// @docImport 'app_lifecycle_listener.dart';
/// @docImport 'basic.dart';
/// @docImport 'focus_scope.dart';
/// @docImport 'media_query.dart';
/// @docImport 'navigator.dart';
/// @docImport 'pop_scope.dart';
library;
import 'dart:async';
import 'dart:developer' as developer;
import 'dart:ui'
show
AccessibilityFeatures,
AppExitResponse,
AppLifecycleState,
FrameTiming,
Locale,
PlatformDispatcher,
TimingsCallback,
ViewFocusEvent;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import '../foundation/_features.dart';
import '_accessibility_evaluations.dart';
import '_window.dart';
import 'app.dart';
import 'debug.dart';
import 'focus_manager.dart';
import 'framework.dart';
import 'platform_menu_bar.dart';
import 'router.dart';
import 'service_extensions.dart';
import 'view.dart';
import 'widget_inspector.dart';
export 'dart:ui' show AppLifecycleState, Locale;
// Examples can assume:
// late FlutterView myFlutterView;
// class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) => const Placeholder(); }
/// Interface for classes that register with the Widgets layer binding.
///
/// This can be used by any class, not just widgets. It provides an interface
/// which is used by [WidgetsBinding.addObserver] and
/// [WidgetsBinding.removeObserver] to notify objects of changes in the
/// environment, such as changes to the device metrics or accessibility
/// settings. It is used to implement features such as [MediaQuery].
///
/// This class can be extended directly, or mixed in, to get default behaviors
/// for all of the handlers. Alternatively it can be used with the
/// `implements` keyword, in which case all the handlers must be implemented
/// (and the analyzer will list those that have been omitted).
///
/// To start receiving notifications, call `WidgetsBinding.instance.addObserver`
/// with a reference to the object implementing the [WidgetsBindingObserver]
/// interface. To avoid memory leaks, call
/// `WidgetsBinding.instance.removeObserver` to unregister the object when it
/// reaches the end of its lifecycle.
///
/// {@tool dartpad}
/// This sample shows how to implement parts of the [State] and
/// [WidgetsBindingObserver] protocols necessary to react to application
/// lifecycle messages. See [didChangeAppLifecycleState].
///
/// To respond to other notifications, replace the [didChangeAppLifecycleState]
/// method in this example with other methods from this class.
///
/// ** See code in examples/api/lib/widgets/binding/widget_binding_observer.0.dart **
/// {@end-tool}
abstract mixin class WidgetsBindingObserver {
/// Called when the system tells the app to pop the current route, such as
/// after a system back button press or back gesture.
///
/// Observers are notified in registration order until one returns
/// true. If none return true, the application quits.
///
/// Observers are expected to return true if they were able to
/// handle the notification, for example by closing an active dialog
/// box, and false otherwise. The [WidgetsApp] widget uses this
/// mechanism to notify the [Navigator] widget that it should pop
/// its current route if possible.
///
/// This method exposes the `popRoute` notification from
/// [SystemChannels.navigation].
///
/// {@macro flutter.widgets.AndroidPredictiveBack}
Future<bool> didPopRoute() => Future<bool>.value(false);
/// Called at the start of a predictive back gesture.
///
/// Observers are notified in registration order until one returns true or all
/// observers have been notified. If an observer returns true then that
/// observer, and only that observer, will be notified of subsequent events in
/// this same gesture (for example [handleUpdateBackGestureProgress], etc.).
///
/// Observers are expected to return true if they were able to handle the
/// notification, for example by starting a predictive back animation, and
/// false otherwise. [PredictiveBackPageTransitionsBuilder] uses this
/// mechanism to listen for predictive back gestures.
///
/// If all observers indicate they are not handling this back gesture by
/// returning false, then a navigation pop will result when
/// [handleCommitBackGesture] is called, as in a non-predictive system back
/// gesture.
///
/// Currently, this is only used on Android devices that support the
/// predictive back feature.
bool handleStartBackGesture(PredictiveBackEvent backEvent) => false;
/// Called when a predictive back gesture moves.
///
/// The observer which was notified of this gesture's [handleStartBackGesture]
/// is the same observer notified for this.
///
/// Currently, this is only used on Android devices that support the
/// predictive back feature.
void handleUpdateBackGestureProgress(PredictiveBackEvent backEvent) {}
/// Called when a predictive back gesture is finished successfully, indicating
/// that the current route should be popped.
///
/// The observer which was notified of this gesture's [handleStartBackGesture]
/// is the same observer notified for this. If there is none, then a
/// navigation pop will result, as in a non-predictive system back gesture.
///
/// Currently, this is only used on Android devices that support the
/// predictive back feature.
void handleCommitBackGesture() {}
/// Called when a predictive back gesture is canceled, indicating that no
/// navigation should occur.
///
/// The observer which was notified of this gesture's [handleStartBackGesture]
/// is the same observer notified for this.
///
/// Currently, this is only used on Android devices that support the
/// predictive back feature.
void handleCancelBackGesture() {}
/// Called when the user taps the status bar on iOS, to scroll a scroll
/// view to the top.
///
/// This event should usually only be handled by at most one scroll view, so
/// implementer(s) of this callback must coordinate to determine the most
/// suitable scroll view for handling this event.
///
/// This callback is only called on iOS. The default implementation provided by
/// [WidgetsBindingObserver] does nothing.
///
/// See also:
///
/// * [Scaffold] and [CupertinoPageScaffold] which use this callback to implement
/// iOS scroll-to-top.
void handleStatusBarTap() {}
/// Called when the host tells the application to push a new route onto the
/// navigator.
///
/// Observers are expected to return true if they were able to
/// handle the notification. Observers are notified in registration
/// order until one returns true.
///
/// This method exposes the `pushRoute` notification from
/// [SystemChannels.navigation].
@Deprecated(
'Use didPushRouteInformation instead. '
'This feature was deprecated after v3.8.0-14.0.pre.',
)
Future<bool> didPushRoute(String route) => Future<bool>.value(false);
/// Called when the host tells the application to push a new
/// [RouteInformation] and a restoration state onto the router.
///
/// Observers are expected to return true if they were able to
/// handle the notification. Observers are notified in registration
/// order until one returns true.
///
/// This method exposes the `pushRouteInformation` notification from
/// [SystemChannels.navigation].
///
/// The default implementation is to call the [didPushRoute] directly with the
/// string constructed from [RouteInformation.uri]'s path and query parameters.
// TODO(chunhtai): remove the default implementation once `didPushRoute` is
// removed.
Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
final Uri uri = routeInformation.uri;
return didPushRoute(
Uri.decodeComponent(
Uri(
path: uri.path.isEmpty ? '/' : uri.path,
queryParameters: uri.queryParametersAll.isEmpty ? null : uri.queryParametersAll,
fragment: uri.fragment.isEmpty ? null : uri.fragment,
).toString(),
),
);
}
/// Called when the application's dimensions change. For example,
/// when a phone is rotated.
///
/// This method exposes notifications from
/// [dart:ui.PlatformDispatcher.onMetricsChanged].
///
/// {@tool snippet}
///
/// This [StatefulWidget] implements the parts of the [State] and
/// [WidgetsBindingObserver] protocols necessary to react when the device is
/// rotated (or otherwise changes dimensions).
///
/// ```dart
/// class MetricsReactor extends StatefulWidget {
/// const MetricsReactor({ super.key });
///
/// @override
/// State<MetricsReactor> createState() => _MetricsReactorState();
/// }
///
/// class _MetricsReactorState extends State<MetricsReactor> with WidgetsBindingObserver {
/// late Size _lastSize;
///
/// @override
/// void initState() {
/// super.initState();
/// WidgetsBinding.instance.addObserver(this);
/// }
///
/// @override
/// void didChangeDependencies() {
/// super.didChangeDependencies();
/// // [View.of] exposes the view from `WidgetsBinding.instance.platformDispatcher.views`
/// // into which this widget is drawn.
/// _lastSize = View.of(context).physicalSize;
/// }
///
/// @override
/// void dispose() {
/// WidgetsBinding.instance.removeObserver(this);
/// super.dispose();
/// }
///
/// @override
/// void didChangeMetrics() {
/// setState(() { _lastSize = View.of(context).physicalSize; });
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// return Text('Current size: $_lastSize');
/// }
/// }
/// ```
/// {@end-tool}
///
/// In general, this is unnecessary as the layout system takes care of
/// automatically recomputing the application geometry when the application
/// size changes.
///
/// See also:
///
/// * [MediaQuery.sizeOf], which provides a similar service with less
/// boilerplate.
void didChangeMetrics() {}
/// Called when the platform's text scale factor changes.
///
/// This typically happens as the result of the user changing system
/// preferences, and it should affect all of the text sizes in the
/// application.
///
/// This method exposes notifications from
/// [dart:ui.PlatformDispatcher.onTextScaleFactorChanged].
///
/// {@tool snippet}
///
/// ```dart
/// class TextScaleFactorReactor extends StatefulWidget {
/// const TextScaleFactorReactor({super.key});
///
/// @override
/// State<TextScaleFactorReactor> createState() => _TextScaleFactorReactorState();
/// }
///
/// class _TextScaleFactorReactorState extends State<TextScaleFactorReactor>
/// with WidgetsBindingObserver {
/// double _lastTextScaleFactor =
/// WidgetsBinding.instance.platformDispatcher.textScaleFactor;
///
/// @override
/// void initState() {
/// super.initState();
/// WidgetsBinding.instance.addObserver(this);
/// }
///
/// @override
/// void dispose() {
/// WidgetsBinding.instance.removeObserver(this);
/// super.dispose();
/// }
///
/// @override
/// void didChangeTextScaleFactor() {
/// setState(() {
/// _lastTextScaleFactor =
/// WidgetsBinding.instance.platformDispatcher.textScaleFactor;
/// });
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// return Text('Current scale factor: $_lastTextScaleFactor');
/// }
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [MediaQuery.textScaleFactorOf], which provides a similar service with less
/// boilerplate.
void didChangeTextScaleFactor() {}
/// Called when the platform brightness changes.
///
/// This method exposes notifications from
/// [dart:ui.PlatformDispatcher.onPlatformBrightnessChanged].
///
/// See also:
///
/// * [MediaQuery.platformBrightnessOf], which provides a similar service with
/// less boilerplate.
void didChangePlatformBrightness() {}
/// Called when the system tells the app that the user's locale has
/// changed. For example, if the user changes the system language
/// settings.
///
/// This method exposes notifications from
/// [dart:ui.PlatformDispatcher.onLocaleChanged].
void didChangeLocales(List<Locale>? locales) {}
/// Called when the system puts the app in the background or returns
/// the app to the foreground.
///
/// An example of implementing this method is provided in the class-level
/// documentation for the [WidgetsBindingObserver] class.
///
/// This method exposes notifications from [SystemChannels.lifecycle].
///
/// See also:
///
/// * [AppLifecycleListener], an alternative API for responding to
/// application lifecycle changes.
void didChangeAppLifecycleState(AppLifecycleState state) {}
/// Called whenever the [PlatformDispatcher] receives a notification that the
/// focus state on a view has changed.
///
/// The [event] contains the view ID for the view that changed its focus
/// state.
///
/// The view ID of the [FlutterView] in which a particular [BuildContext]
/// resides can be retrieved with `View.of(context).viewId`, so that it may be
/// compared with the view ID in the `event` to see if the event pertains to
/// the given context.
void didChangeViewFocus(ViewFocusEvent event) {}
/// Called when a request is received from the system to exit the application.
///
/// If any observer responds with [AppExitResponse.cancel], it will cancel the
/// exit. All observers will be asked before exiting.
///
/// {@macro flutter.services.binding.ServicesBinding.requestAppExit}
///
/// See also:
///
/// * [ServicesBinding.exitApplication] for a function to call that will request
/// that the application exits.
Future<AppExitResponse> didRequestAppExit() async {
return AppExitResponse.exit;
}
/// Called when the system is running low on memory.
///
/// This method exposes the `memoryPressure` notification from
/// [SystemChannels.system].
void didHaveMemoryPressure() {}
/// Called when the system changes the set of currently active accessibility
/// features.
///
/// This method exposes notifications from
/// [dart:ui.PlatformDispatcher.onAccessibilityFeaturesChanged].
void didChangeAccessibilityFeatures() {}
}
/// The glue between the widgets layer and the Flutter engine.
///
/// The [WidgetsBinding] manages a single [Element] tree rooted at [rootElement].
/// Calling [runApp] (which indirectly calls [attachRootWidget]) bootstraps that
/// element tree.
///
/// ## Relationship to render trees
///
/// Multiple render trees may be associated with the element tree. Those are
/// managed by the underlying [RendererBinding].
///
/// The element tree is segmented into two types of zones: rendering zones and
/// non-rendering zones.
///
/// A rendering zone is a part of the element tree that is backed by a render
/// tree and it describes the pixels that are drawn on screen. For elements in
/// this zone, [Element.renderObject] never returns null because the elements
/// are all associated with [RenderObject]s. Almost all widgets can be placed in
/// a rendering zone; notable exceptions are the [View] widget, [ViewCollection]
/// widget, and [RootWidget].
///
/// A non-rendering zone is a part of the element tree that is not backed by a
/// render tree. For elements in this zone, [Element.renderObject] returns null
/// because the elements are not associated with any [RenderObject]s. Only
/// widgets that do not produce a [RenderObject] can be used in this zone
/// because there is no render tree to attach the render object to. In other
/// words, [RenderObjectWidget]s cannot be used in this zone. Typically, one
/// would find [InheritedWidget]s, [View]s, and [ViewCollection]s in this zone
/// to inject data across rendering zones into the tree and to organize the
/// rendering zones (and by extension their associated render trees) into a
/// unified element tree.
///
/// The root of the element tree at [rootElement] starts a non-rendering zone.
/// Within a non-rendering zone, the [View] widget is used to start a rendering
/// zone by bootstrapping a render tree. Within a rendering zone, the
/// [ViewAnchor] can be used to start a new non-rendering zone.
///
// TODO(goderbauer): Include an example graph showcasing the different zones.
///
/// To figure out if an element is in a rendering zone it may walk up the tree
/// calling [Element.debugExpectsRenderObjectForSlot] on its ancestors. If it
/// reaches an element that returns false, it is in a non-rendering zone. If it
/// reaches a [RenderObjectElement] ancestor it is in a rendering zone.
mixin WidgetsBinding
on
BindingBase,
ServicesBinding,
SchedulerBinding,
GestureBinding,
RendererBinding,
SemanticsBinding {
@override
void initInstances() {
super.initInstances();
_instance = this;
assert(() {
_debugAddStackFilters();
return true;
}());
// Initialization of [_buildOwner] has to be done after
// [super.initInstances] is called, as it requires [ServicesBinding] to
// properly setup the [defaultBinaryMessenger] instance.
_buildOwner = BuildOwner();
buildOwner!.onBuildScheduled = _handleBuildScheduled;
platformDispatcher.onLocaleChanged = handleLocaleChanged;
SystemChannels.navigation.setMethodCallHandler(_handleNavigationInvocation);
SystemChannels.backGesture.setMethodCallHandler(_handleBackGestureInvocation);
SystemChannels.statusBar.setMethodCallHandler(_handleStatusBarActions);
assert(() {
FlutterErrorDetails.propertiesTransformers.add(debugTransformDebugCreator);
return true;
}());
platformMenuDelegate = DefaultPlatformMenuDelegate();
_windowingOwner = createDefaultWindowingOwner();
}
/// The current [WidgetsBinding], if one has been created.
///
/// Provides access to the features exposed by this mixin. The binding must
/// be initialized before using this getter; this is typically done by calling
/// [runApp] or [WidgetsFlutterBinding.ensureInitialized].
static WidgetsBinding get instance => BindingBase.checkInstance(_instance);
static WidgetsBinding? _instance;
/// If true, forces the widget inspector to be visible.
///
/// Overrides the `debugShowWidgetInspector` value set in [WidgetsApp].
///
/// Used by the `debugShowWidgetInspector` debugging extension.
///
/// The inspector allows the selection of a location on your device or emulator
/// and view what widgets and render objects associated with it. An outline of
/// the selected widget and some summary information is shown on device and
/// more detailed information is shown in the IDE or DevTools.
bool get debugShowWidgetInspectorOverride {
return debugShowWidgetInspectorOverrideNotifier.value;
}
set debugShowWidgetInspectorOverride(bool value) {
debugShowWidgetInspectorOverrideNotifier.value = value;
}
/// Notifier for [debugShowWidgetInspectorOverride].
ValueNotifier<bool> get debugShowWidgetInspectorOverrideNotifier =>
_debugShowWidgetInspectorOverrideNotifierObject ??= ValueNotifier<bool>(false);
ValueNotifier<bool>? _debugShowWidgetInspectorOverrideNotifierObject;
/// The notifier for whether or not taps on the device are treated as widget
/// selections when the widget inspector is enabled.
///
/// - If true, taps in the app are intercepted by the widget inspector.
/// - If false, taps in the app are not intercepted by the widget inspector.
ValueNotifier<bool> get debugWidgetInspectorSelectionOnTapEnabled =>
_debugWidgetInspectorSelectionOnTapEnabledNotifierObject ??= ValueNotifier<bool>(true);
ValueNotifier<bool>? _debugWidgetInspectorSelectionOnTapEnabledNotifierObject;
/// If true, [WidgetInspector] will not be automatically injected into the
/// widget tree.
///
/// This overrides the behavior where [WidgetInspector] is added to the
/// widget tree created by [WidgetsApp] when the `debugShowWidgetInspector`
/// value is set in [WidgetsApp] or [debugShowWidgetInspectorOverride] is set
/// to true.
///
/// Used by tools that want more control over which widgets can be selected
/// and highlighted by the widget inspector by manually injecting instances of
/// [WidgetInspector].
bool get debugExcludeRootWidgetInspector => _debugExcludeRootWidgetInspector;
set debugExcludeRootWidgetInspector(bool value) {
_debugExcludeRootWidgetInspector = value;
}
bool _debugExcludeRootWidgetInspector = false;
@visibleForTesting
@override
void resetInternalState() {
// ignore: invalid_use_of_visible_for_testing_member, https://github.com/dart-lang/sdk/issues/41998
super.resetInternalState();
_debugShowWidgetInspectorOverrideNotifierObject?.dispose();
_debugShowWidgetInspectorOverrideNotifierObject = null;
_debugWidgetInspectorSelectionOnTapEnabledNotifierObject?.dispose();
_debugWidgetInspectorSelectionOnTapEnabledNotifierObject = null;
}
void _debugAddStackFilters() {
const elementInflateWidget = PartialStackFrame(
package: 'package:flutter/src/widgets/framework.dart',
className: 'Element',
method: 'inflateWidget',
);
const elementUpdateChild = PartialStackFrame(
package: 'package:flutter/src/widgets/framework.dart',
className: 'Element',
method: 'updateChild',
);
const elementRebuild = PartialStackFrame(
package: 'package:flutter/src/widgets/framework.dart',
className: 'Element',
method: 'rebuild',
);
const componentElementPerformRebuild = PartialStackFrame(
package: 'package:flutter/src/widgets/framework.dart',
className: 'ComponentElement',
method: 'performRebuild',
);
const componentElementFirstBuild = PartialStackFrame(
package: 'package:flutter/src/widgets/framework.dart',
className: 'ComponentElement',
method: '_firstBuild',
);
const componentElementMount = PartialStackFrame(
package: 'package:flutter/src/widgets/framework.dart',
className: 'ComponentElement',
method: 'mount',
);
const statefulElementFirstBuild = PartialStackFrame(
package: 'package:flutter/src/widgets/framework.dart',
className: 'StatefulElement',
method: '_firstBuild',
);
const singleChildMount = PartialStackFrame(
package: 'package:flutter/src/widgets/framework.dart',
className: 'SingleChildRenderObjectElement',
method: 'mount',
);
const statefulElementRebuild = PartialStackFrame(
package: 'package:flutter/src/widgets/framework.dart',
className: 'StatefulElement',
method: 'performRebuild',
);
const replacementString = '... Normal element mounting';
// ComponentElement variations
FlutterError.addDefaultStackFilter(
const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[
elementInflateWidget,
elementUpdateChild,
componentElementPerformRebuild,
elementRebuild,
componentElementFirstBuild,
componentElementMount,
],
replacement: replacementString,
),
);
FlutterError.addDefaultStackFilter(
const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[
elementUpdateChild,
componentElementPerformRebuild,
elementRebuild,
componentElementFirstBuild,
componentElementMount,
],
replacement: replacementString,
),
);
// StatefulElement variations
FlutterError.addDefaultStackFilter(
const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[
elementInflateWidget,
elementUpdateChild,
componentElementPerformRebuild,
statefulElementRebuild,
elementRebuild,
componentElementFirstBuild,
statefulElementFirstBuild,
componentElementMount,
],
replacement: replacementString,
),
);
FlutterError.addDefaultStackFilter(
const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[
elementUpdateChild,
componentElementPerformRebuild,
statefulElementRebuild,
elementRebuild,
componentElementFirstBuild,
statefulElementFirstBuild,
componentElementMount,
],
replacement: replacementString,
),
);
// SingleChildRenderObjectElement variations
FlutterError.addDefaultStackFilter(
const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[elementInflateWidget, elementUpdateChild, singleChildMount],
replacement: replacementString,
),
);
FlutterError.addDefaultStackFilter(
const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[elementUpdateChild, singleChildMount],
replacement: replacementString,
),
);
}
@override
void initServiceExtensions() {
super.initServiceExtensions();
if (!kReleaseMode) {
registerServiceExtension(
name: WidgetsServiceExtensions.debugDumpApp.name,
callback: (Map<String, String> parameters) async {
final String data = _debugDumpAppString();
return <String, Object>{'data': data};
},
);
registerServiceExtension(
name: WidgetsServiceExtensions.debugDumpFocusTree.name,
callback: (Map<String, String> parameters) async {
final String data = focusManager.toStringDeep();
return <String, Object>{'data': data};
},
);
if (!kIsWeb) {
registerBoolServiceExtension(
name: WidgetsServiceExtensions.showPerformanceOverlay.name,
getter: () => Future<bool>.value(WidgetsApp.showPerformanceOverlayOverride),
setter: (bool value) {
if (WidgetsApp.showPerformanceOverlayOverride == value) {
return Future<void>.value();
}
WidgetsApp.showPerformanceOverlayOverride = value;
return _forceRebuild();
},
);
}
registerServiceExtension(
name: WidgetsServiceExtensions.didSendFirstFrameEvent.name,
callback: (_) async {
return <String, dynamic>{
// This is defined to return a STRING, not a boolean.
// Devtools, the Intellij plugin, and the flutter tool all depend
// on it returning a string and not a boolean.
'enabled': _needToReportFirstFrame ? 'false' : 'true',
};
},
);
registerServiceExtension(
name: WidgetsServiceExtensions.didSendFirstFrameRasterizedEvent.name,
callback: (_) async {
return <String, dynamic>{
// This is defined to return a STRING, not a boolean.
// Devtools, the Intellij plugin, and the flutter tool all depend
// on it returning a string and not a boolean.
'enabled': firstFrameRasterized ? 'true' : 'false',
};
},
);
// Expose the ability to send Widget rebuilds as [Timeline] events.
registerBoolServiceExtension(
name: WidgetsServiceExtensions.profileWidgetBuilds.name,
getter: () async => debugProfileBuildsEnabled,
setter: (bool value) async {
debugProfileBuildsEnabled = value;
},
);
registerBoolServiceExtension(
name: WidgetsServiceExtensions.profileUserWidgetBuilds.name,
getter: () async => debugProfileBuildsEnabledUserWidgets,
setter: (bool value) async {
debugProfileBuildsEnabledUserWidgets = value;
},
);
registerServiceExtension(
name: WidgetsServiceExtensions.accessibilityEvaluations.name,
callback: (Map<String, String> parameters) async {
final String? type = parameters['type'];
if (type == null) {
throw Exception('type parameter is required');
}
switch (type) {
case 'MinimumTextContrastEvaluation':
if (parameters case {
'minNormalTextContrastRatio': final String minNormalTextContrastRatio,
'minLargeTextContrastRatio': final String minLargeTextContrastRatio,
}) {
final EvaluationResult result = await MinimumTextContrastEvaluation(
minNormalTextContrastRatio: double.parse(minNormalTextContrastRatio),
minLargeTextContrastRatio: double.parse(minLargeTextContrastRatio),
).evaluate(this);
return _formatEvaluationResult(result.violations);
}
throw Exception('Invalid arguments');
case 'MinimumTapTargetEvaluation':
if (parameters case {'targetSize': final String targetSize}) {
final EvaluationResult result = await MinimumTapTargetEvaluation(
size: Size.square(double.parse(targetSize)),
).evaluate(this);
return _formatEvaluationResult(result.violations);
}
throw Exception('Invalid arguments');
case 'LabeledTapTargetEvaluation':
final EvaluationResult result = await const LabeledTapTargetEvaluation().evaluate(
this,
);
return _formatEvaluationResult(result.violations);
default:
throw Exception('unknown type: $type');
}
},
);
}
assert(() {
registerBoolServiceExtension(
name: WidgetsServiceExtensions.debugAllowBanner.name,
getter: () => Future<bool>.value(WidgetsApp.debugAllowBannerOverride),
setter: (bool value) {
if (WidgetsApp.debugAllowBannerOverride == value) {
return Future<void>.value();
}
WidgetsApp.debugAllowBannerOverride = value;
return _forceRebuild();
},
);
WidgetInspectorService.instance.initServiceExtensions(registerServiceExtension);
return true;
}());
}
Map<String, List<Map<String, String>>> _formatEvaluationResult(List<Violation> violations) {
return <String, List<Map<String, String>>>{
'result': violations.map((Violation violation) {
return <String, String>{
'nodeId': violation.node.id.toString(),
'message': violation.reason,
};
}).toList(),
};
}
Future<void> _forceRebuild() {
if (rootElement != null) {
buildOwner!.reassemble(rootElement!);
return endOfFrame;
}
return Future<void>.value();
}
/// The [BuildOwner] in charge of executing the build pipeline for the
/// widget tree rooted at this binding.
BuildOwner? get buildOwner => _buildOwner;
// Initialization of [_buildOwner] has to be done within the [initInstances]
// method, as it requires [ServicesBinding] to properly setup the
// [defaultBinaryMessenger] instance.
BuildOwner? _buildOwner;
/// The object in charge of the focus tree.
///
/// Rarely used directly. Instead, consider using [FocusScope.of] to obtain
/// the [FocusScopeNode] for a given [BuildContext].
///
/// See [FocusManager] for more details.
FocusManager get focusManager => _buildOwner!.focusManager;
/// A delegate that communicates with a platform plugin for serializing and
/// managing platform-rendered menu bars created by [PlatformMenuBar].
///
/// This is set by default to a [DefaultPlatformMenuDelegate] instance in
/// [initInstances].
late PlatformMenuDelegate platformMenuDelegate;
final List<WidgetsBindingObserver> _observers = <WidgetsBindingObserver>[];
/// Registers the given object as a binding observer. Binding
/// observers are notified when various application events occur,
/// for example when the system locale changes. Generally, one
/// widget in the widget tree registers itself as a binding
/// observer, and converts the system state into inherited widgets.
///
/// For example, the [WidgetsApp] widget registers as a binding
/// observer and passes the screen size to a [MediaQuery] widget
/// each time it is built, which enables other widgets to use the
/// [MediaQuery.sizeOf] static method and (implicitly) the
/// [InheritedWidget] mechanism to be notified whenever the screen
/// size changes (e.g. whenever the screen rotates).
///
/// See also:
///
/// * [removeObserver], to release the resources reserved by this method.
/// * [WidgetsBindingObserver], which has an example of using this method.
void addObserver(WidgetsBindingObserver observer) => _observers.add(observer);
/// Unregisters the given observer. This should be used sparingly as
/// it is relatively expensive (O(N) in the number of registered
/// observers).
///
/// See also:
///
/// * [addObserver], for the method that adds observers in the first place.
/// * [WidgetsBindingObserver], which has an example of using this method.
bool removeObserver(WidgetsBindingObserver observer) {
_backGestureObservers.remove(observer);
return _observers.remove(observer);
}
@override
Future<AppExitResponse> handleRequestAppExit() async {
var didCancel = false;
for (final observer in List<WidgetsBindingObserver>.of(_observers)) {
try {
if ((await observer.didRequestAppExit()) == AppExitResponse.cancel) {
didCancel = true;
// Don't early return. For the case where someone is just using the
// observer to know when exit happens, we want to call all the
// observers, even if we already know we're going to cancel.
}
} catch (exception, stack) {
FlutterError.reportError(
FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets library',
context: ErrorDescription(
'while dispatching notifications for WidgetsBindingObserver.didRequestAppExit',
),
),
);
}
}
return didCancel ? AppExitResponse.cancel : AppExitResponse.exit;
}
@override
void handleMetricsChanged() {
super.handleMetricsChanged();
for (final observer in List<WidgetsBindingObserver>.of(_observers)) {
try {
observer.didChangeMetrics();
} catch (exception, stack) {
FlutterError.reportError(
FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets library',
context: ErrorDescription(
'while dispatching notifications for WidgetsBindingObserver.didChangeMetrics',
),
),
);
}
}
}
@override
void handleTextScaleFactorChanged() {
super.handleTextScaleFactorChanged();
for (final observer in List<WidgetsBindingObserver>.of(_observers)) {
try {
observer.didChangeTextScaleFactor();
} catch (exception, stack) {
FlutterError.reportError(
FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets library',
context: ErrorDescription(
'while dispatching notifications for WidgetsBindingObserver.didChangeTextScaleFactor',
),
),
);
}
}
}
@override
void handlePlatformBrightnessChanged() {
super.handlePlatformBrightnessChanged();
for (final observer in List<WidgetsBindingObserver>.of(_observers)) {
try {
observer.didChangePlatformBrightness();
} catch (exception, stack) {
FlutterError.reportError(
FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets library',
context: ErrorDescription(
'while dispatching notifications for WidgetsBindingObserver.didChangePlatformBrightness',
),
),
);
}
}
}
@override
void handleAccessibilityFeaturesChanged() {
super.handleAccessibilityFeaturesChanged();
for (final observer in List<WidgetsBindingObserver>.of(_observers)) {
try {
observer.didChangeAccessibilityFeatures();
} catch (exception, stack) {
FlutterError.reportError(
FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets library',
context: ErrorDescription(
'while dispatching notifications for WidgetsBindingObserver.didChangeAccessibilityFeatures',
),
),
);