TestWidgetsFlutterBinding class Null safety

Base class for bindings used by widgets library tests.

The ensureInitialized method creates (if necessary) and returns an instance of the appropriate subclass. (If one is already created, it returns that one, even if it's not the one that it would normally create. This allows tests to force the use of LiveTestWidgetsFlutterBinding even in a normal unit test environment, e.g. to test that binding.)

When using these bindings, certain features are disabled. For example, timeDilation is reset to 1.0 on initialization.

In non-browser tests, the binding overrides HttpClient creation with a fake client that always returns a status code of 400. This is to prevent tests from making network calls, which could introduce flakiness. A test that actually needs to make a network call should provide its own HttpClient to the code making the call, so that it can appropriately mock or fake responses.

Coordinate spaces

TestWidgetsFlutterBinding might be run on devices of different screen sizes, while the testing widget is still told the same size to ensure consistent results. Consequently, code that deals with positions (such as pointer events or painting) must distinguish between two coordinate spaces:

  • The local coordinate space is the one used by the testing widget (typically an 800 by 600 window, but can be altered by setSurfaceSize).
  • The global coordinate space is the one used by the device.

Positions can be transformed between coordinate spaces with localToGlobal and globalToLocal.

Mixed in types


Constructor for TestWidgetsFlutterBinding.


accessibilityFeatures AccessibilityFeatures
The currently active set of AccessibilityFeatures.
read-only, inherited
buildOwner BuildOwner?
The BuildOwner in charge of executing the build pipeline for the widget tree rooted at this binding.
read-only, inherited
channelBuffers ChannelBuffers
The low level buffering and dispatch mechanism for messages sent by plugins on the engine side to their corresponding plugin code on the framework side.
read-only, inherited
clock Clock
The current time.
currentFrameTimeStamp Duration
The time stamp for the frame currently being processed.
read-only, inherited
currentSystemFrameTimeStamp Duration
The raw time stamp as provided by the engine to dart:ui.PlatformDispatcher.onBeginFrame for the frame currently being processed.
read-only, inherited
debugBuildingDirtyElements bool
Whether we are currently in a frame. This is used to verify that frames are not scheduled redundantly.
@protected, read / write, inherited
debugDidSendFirstFrameEvent bool
Whether the first frame has finished building.
read-only, inherited
debugPrintOverride DebugPrintCallback
The value to set debugPrint to while tests are running.
debugSamplingClock SamplingClock?
Overrides the sampling clock for debugging and testing.
@protected, read-only, inherited
defaultBinaryMessenger TestDefaultBinaryMessenger
The default instance of BinaryMessenger.
read-only, inherited
defaultTestTimeout Timeout
The default test timeout for tests when using this binding.
disableAnimations bool
The platform is requesting that animations be disabled or simplified.
read-only, inherited
disableShadows bool
The value to set debugDisableShadows to while tests are running.
@protected, read-only
endOfFrame Future<void>
Returns a Future that completes after the frame completes.
read-only, inherited
firstFrameRasterized bool
Whether the Flutter engine has rasterized the first frame.
read-only, inherited
focusedEditable EditableTextState?
The State of the current EditableText client of the onscreen keyboard.
read / write
focusManager FocusManager
The object in charge of the focus tree.
read-only, inherited
framesEnabled bool
Whether frames are currently being scheduled when scheduleFrame is called.
read-only, inherited
gestureArena GestureArenaManager
The gesture arenas used for disambiguating the meaning of sequences of pointer events.
final, inherited
hashCode int
The hash code for this object.
read-only, inherited
hasScheduledFrame bool
Whether this scheduler has requested that handleBeginFrame be called soon.
read-only, inherited
imageCache ImageCache
The singleton that implements the Flutter framework's image cache.
read-only, inherited
inTest bool
Whether there is currently a test executing.
isRootWidgetAttached bool
Whether the renderViewElement has been initialized.
read-only, inherited
keyboard HardwareKeyboard
The global singleton instance of HardwareKeyboard, which can be used to query keyboard states.
read-only, inherited
keyEventManager KeyEventManager
The global singleton instance of KeyEventManager, which is used internally to dispatch key messages.
read-only, inherited
lifecycleState AppLifecycleState?
Whether the application is visible, and if so, whether it is currently interactive.
read-only, inherited
locked bool
Whether lockEvents is currently locking events.
@protected, read-only, inherited
microtaskCount int
The number of outstanding microtasks in the queue.
mouseTracker MouseTracker
The object that manages state about currently connected mice, for hover notification.
read-only, inherited
overrideHttpClient bool
Determines whether the Dart HttpClient class should be overridden to always return a failure response.
@protected, read-only
pipelineOwner PipelineOwner
The render tree's owner, which maintains dirty state for layout, composite, paint, and accessibility semantics.
read-only, inherited
platformDispatcher TestPlatformDispatcher
The ui.PlatformDispatcher to which this binding is bound.
read-only, override
platformMenuDelegate PlatformMenuDelegate
A delegate that communicates with a platform plugin for serializing and managing platform-rendered menu bars created by PlatformMenuBar.
read / write, inherited
pointerEventSource TestBindingEventSource
The source of the current pointer event.
pointerRouter PointerRouter
A router that routes all pointer events received from the engine.
final, inherited
pointerSignalResolver PointerSignalResolver
The resolver used for determining which widget handles a PointerSignalEvent.
final, inherited
registerTestTextInput bool
Determines whether the binding automatically registers testTextInput as a fake keyboard implementation.
@protected, read-only
renderView RenderView
The render tree that's attached to the output surface.
read / write, inherited
renderViewElement Element?
The Element that is at the root of the hierarchy (and which wraps the RenderView object at the root of the rendering hierarchy).
read-only, inherited
resamplingEnabled bool
Enable pointer event resampling for touch devices by setting this to true.
read / write, inherited
restorationManager TestRestorationManager
The RestorationManager synchronizes the restoration data between engine and framework.
read-only, override
runtimeType Type
A representation of the runtime type of the object.
read-only, inherited
samplingOffset Duration
Offset relative to current frame time that should be used for resampling. The samplingOffset is expected to be negative. Non-negative samplingOffset is allowed but will effectively disable resampling.
read / write, inherited
schedulerPhase SchedulerPhase
The phase that the scheduler is currently operating under.
read-only, inherited
schedulingStrategy SchedulingStrategy
The strategy to use when deciding whether to run a task or not.
read / write, inherited
sendFramesToEngine bool
Whether frames produced by drawFrame are sent to the engine.
read-only, inherited
showAppDumpInErrors bool
Whether to include the output of debugDumpApp() when reporting test failures.
read / write
systemFonts Listenable
Listenable that notifies when the available fonts on the system have changed.
read-only, inherited
testTextInput TestTextInput
A stub for the system's onscreen keyboard. Callers must set the focusedEditable before using this value.
transientCallbackCount int
The current number of transient frame callbacks scheduled.
read-only, inherited
waitUntilFirstFrameRasterized Future<void>
A future that completes when the Flutter engine has rasterized the first frame.
read-only, inherited
window TestWindow
The main window to which this binding is bound.
read-only, override


addObserver(WidgetsBindingObserver observer) → void
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.
addPersistentFrameCallback(FrameCallback callback) → void
Adds a persistent frame callback.
addPostFrameCallback(FrameCallback callback) → void
Schedule a callback for the end of this frame.
addTime(Duration duration) → void
This method has no effect.
@Deprecated('This method has no effect. ' 'This feature was deprecated after v2.6.0-1.0.pre.')
addTimingsCallback(TimingsCallback callback) → void
Add a TimingsCallback that receives FrameTiming sent from the engine.
allowFirstFrame() → void
Called after deferFirstFrame to tell the framework that it is ok to send the first frame to the engine now.
asyncBarrier() → void
This is called during test execution before and after the body has been executed.
attachRootWidget(Widget rootWidget) → void
Takes a widget and attaches it to the renderViewElement, creating it if necessary.
cancelFrameCallbackWithId(int id) → void
Cancels the transient frame callback with the given id.
cancelPointer(int pointer) → void
Dispatch a PointerCancelEvent for the given pointer soon.
computePlatformResolvedLocale(List<Locale> supportedLocales) Locale?
Computes the locale the current platform would resolve to.
createBinaryMessenger() TestDefaultBinaryMessenger
Creates a default BinaryMessenger instance that can be used for sending platform messages.
createImageCache() ImageCache
Creates the ImageCache singleton (accessible via imageCache).
@protected, inherited
createRestorationManager() TestRestorationManager
Creates the RestorationManager instance available via restorationManager.
createSemanticsUpdateBuilder() SemanticsUpdateBuilder
Creates an empty semantics update builder.
createViewConfiguration() ViewConfiguration
Returns a ViewConfiguration configured for the RenderView based on the current environment.
debugAssertNoTransientCallbacks(String reason) bool
Asserts that there are no registered transient callbacks; if there are, prints their locations and throws an exception.
deferFirstFrame() → void
Tell the framework to not send the first frames to the engine until there is a corresponding call to allowFirstFrame.
delayed(Duration duration) Future<void>
Delay for duration of time.
dispatchAccessibilityFeaturesChanged() → void
Notify all the observers that the active set of AccessibilityFeatures has changed (using WidgetsBindingObserver.didChangeAccessibilityFeatures), giving them the features argument.
@mustCallSuper, @protected, inherited
dispatchEvent(PointerEvent event, HitTestResult? hitTestResult) → void
Dispatch an event to pointerRouter and the path of a hit test result.
dispatchLocalesChanged(List<Locale>? locales) → void
Notify all the observers that the locale has changed (using WidgetsBindingObserver.didChangeLocales), giving them the locales argument.
@mustCallSuper, @protected, inherited
drawFrame() → void
Pump the build and rendering pipeline to generate a frame.
ensureFrameCallbacksRegistered() → void
Ensures callbacks for PlatformDispatcher.onBeginFrame and PlatformDispatcher.onDrawFrame are registered.
@protected, inherited
ensureVisualUpdate() → void
Schedules a new frame using scheduleFrame if this object is not currently producing a frame.
evict(String asset) → void
Called in response to the ext.flutter.evict service extension.
globalToLocal(Offset point) Offset
Convert the given point from the global coordinate space to the local one.
handleAccessibilityFeaturesChanged() → void
Called when the platform accessibility features change.
handleAppLifecycleStateChanged(AppLifecycleState state) → void
Called when the application lifecycle state changes.
handleBeginFrame(Duration? rawTimeStamp) → void
Called by the engine to prepare the framework to produce a new frame.
handleDrawFrame() → void
Called by the engine to produce a new frame.
handleEvent(PointerEvent event, HitTestEntry<HitTestTarget> entry) → void
Override this method to receive events.
handleEventLoopCallback() bool
Execute the highest-priority task, if it is of a high enough priority.
@visibleForTesting, inherited
handleLocaleChanged() → void
Called when the system locale changes.
@mustCallSuper, @protected, inherited
handleMemoryPressure() → void
Called when the operating system notifies the application of a memory pressure situation.
handleMetricsChanged() → void
Called when the system metrics change.
handlePlatformBrightnessChanged() → void
Called when the platform brightness changes.
handlePointerEvent(PointerEvent event) → void
Dispatch an event to the targets found by a hit test on its position.
handlePointerEventForSource(PointerEvent event, {TestBindingEventSource source = TestBindingEventSource.device}) → void
Dispatch an event to the targets found by a hit test on its position, and remember its source as pointerEventSource.
handlePopRoute() Future<void>
Called when the system pops the current route.
@protected, inherited
handlePushRoute(String route) Future<void>
Called when the host tells the app to push a new route onto the navigator.
@mustCallSuper, @protected, inherited
handleSystemMessage(Object systemMessage) Future<void>
Handler called for messages received on the SystemChannels.system message channel.
handleTextScaleFactorChanged() → void
Called when the platform text scale factor changes.
hitTest(HitTestResult result, Offset position) → void
Determine which HitTestTarget objects are located at a given position.
idle() Future<void>
Acts as if the application went idle.
initInstances() → void
The initialization method. Subclasses override this method to hook into the platform and otherwise configure their services. Subclasses must call "super.initInstances()".
initLicenses() → void
Adds relevant licenses to the LicenseRegistry.
initMouseTracker([MouseTracker? tracker]) → void
Creates a MouseTracker which manages state about currently connected mice, for hover notification.
@visibleForTesting, inherited
initRenderView() → void
Creates a RenderView object to be the root of the RenderObject rendering tree, and initializes it so that it will be rendered when the next frame is requested.
initServiceExtensions() → void
Called when the binding is initialized, to register service extensions.
instantiateImageCodec(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) Future<Codec>
Calls through to dart:ui.instantiateImageCodec from ImageCache.
@Deprecated('Use instantiateImageCodecFromBuffer with an ImmutableBuffer instance instead. ' 'This feature was deprecated after v2.13.0-1.0.pre.'), inherited
instantiateImageCodecFromBuffer(ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) Future<Codec>
Calls through to dart:ui.instantiateImageCodecFromBuffer from ImageCache.
localToGlobal(Offset point) Offset
Convert the given point from the local coordinate space to the global one.
lockEvents(Future<void> callback()) Future<void>
Locks the dispatching of asynchronous events and callbacks until the callback's future completes.
@protected, inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a non-existent method or property is accessed.
performReassemble() Future<void>
This method is called by reassembleApplication to actually cause the application to reassemble, e.g. after a hot reload.
postEvent(String eventKind, Map<String, dynamic> eventData) → void
All events dispatched by a BindingBase use this method instead of calling developer.postEvent directly so that tests for BindingBase can track which events were dispatched by overriding this method.
@protected, inherited
postTest() → void
Called by the testWidgets function after a test is executed.
pump([Duration? duration, EnginePhase newPhase = EnginePhase.sendSemanticsUpdate]) Future<void>
Triggers a frame sequence (build/layout/paint/etc), then flushes microtasks.
readInitialLifecycleStateFromNativeWindow() → void
Initializes the lifecycleState with the dart:ui.PlatformDispatcher.initialLifecycleState.
@protected, inherited
readTestInitialLifecycleStateFromNativeWindow() → void
Re-attempts the initialization of the lifecycle state after providing test values in TestWindow.initialLifecycleStateTestValue.
reassembleApplication() Future<void>
Cause the entire application to redraw, e.g. after a hot reload.
registerBoolServiceExtension({required String name, required AsyncValueGetter<bool> getter, required AsyncValueSetter<bool> setter}) → void
Registers a service extension method with the given name (full name "ext.flutter.name"), which takes a single argument "enabled" which can have the value "true" or the value "false" or can be omitted to read the current value. (Any value other than "true" is considered equivalent to "false". Other arguments are ignored.)
@protected, inherited
registerNumericServiceExtension({required String name, required AsyncValueGetter<double> getter, required AsyncValueSetter<double> setter}) → void
Registers a service extension method with the given name (full name "ext.flutter.name"), which takes a single argument with the same name as the method which, if present, must have a value that can be parsed by double.parse, and can be omitted to read the current value. (Other arguments are ignored.)
@protected, inherited
registerServiceExtension({required String name, required ServiceExtensionCallback callback}) → void
Registers a service extension method with the given name (full name "ext.flutter.name").
@protected, inherited
registerSignalServiceExtension({required String name, required AsyncCallback callback}) → void
Registers a service extension method with the given name (full name "ext.flutter.name"), which takes no arguments and returns no value.
@protected, inherited
registerStringServiceExtension({required String name, required AsyncValueGetter<String> getter, required AsyncValueSetter<String> setter}) → void
Registers a service extension method with the given name (full name "ext.flutter.name"), which optionally takes a single argument with the name "value". If the argument is omitted, the value is to be read, otherwise it is to be set. Returns the current value.
@protected, inherited
removeObserver(WidgetsBindingObserver observer) bool
Unregisters the given observer. This should be used sparingly as it is relatively expensive (O(N) in the number of registered observers).
removeTimingsCallback(TimingsCallback callback) → void
Removes a callback that was earlier added by addTimingsCallback.
reportExceptionNoticed(FlutterErrorDetails exception) → void
Called when the framework catches an exception, even if that exception is being handled by takeException.
reset() → void
Called by the test framework at the beginning of a widget test to prepare the binding for the next test.
resetEpoch() → void
Prepares the scheduler for a non-monotonic change to how time stamps are calculated.
resetFirstFrameSent() → void
Call this to pretend that no frames have been sent to the engine yet.
resetGestureBinding() → void
Reset states of GestureBinding.
@protected, inherited
runAsync<T>(Future<T> callback(), {Duration additionalTime = const Duration(milliseconds: 1000)}) Future<T?>
Runs a callback that performs real asynchronous work.
runTest(Future<void> testBody(), VoidCallback invariantTester, {String description = '', Duration? timeout}) Future<void>
Call the testBody inside a FakeAsync scope on which pump can advance time.
scheduleAttachRootWidget(Widget rootWidget) → void
Schedules a Timer for attaching the root widget.
@protected, inherited
scheduleForcedFrame() → void
Schedules a new frame by calling dart:ui.PlatformDispatcher.scheduleFrame.
scheduleFrame() → void
If necessary, schedules a new frame by calling dart:ui.PlatformDispatcher.scheduleFrame.
scheduleFrameCallback(FrameCallback callback, {bool rescheduling = false}) int
Schedules the given transient frame callback.
scheduleTask<T>(TaskCallback<T> task, Priority priority, {String? debugLabel, Flow? flow}) Future<T>
Schedules the given task with the given priority and returns a Future that completes to the task's eventual return value.
scheduleWarmUpFrame() → void
Schedule a frame to run as soon as possible, rather than waiting for the engine to request a frame in response to a system "Vsync" signal.
setLocale(String languageCode, String countryCode) Future<void>
Artificially calls dispatchLocalesChanged on the Widget binding, then flushes microtasks.
setLocales(List<Locale> locales) Future<void>
Artificially calls dispatchLocalesChanged on the Widget binding, then flushes microtasks.
setSemanticsEnabled(bool enabled) → void
Whether the render tree associated with this binding should produce a tree of SemanticsNode objects.
setSurfaceSize(Size? size) Future<void>
Artificially changes the surface size to size on the Widget binding, then flushes microtasks.
setSystemUiChangeCallback(SystemUiChangeCallback? callback) → void
Sets the callback for the SystemChrome.systemUIChange method call received on the SystemChannels.platform channel.
takeException() → dynamic
Returns the exception most recently caught by the Flutter framework.
toString() String
A string representation of this object.
unlocked() → void
Called by lockEvents when events get unlocked.
withPointerEventSource(TestBindingEventSource source, VoidCallback task) → void
Sets pointerEventSource to source, runs task, then resets source to the previous value.


operator ==(Object other) bool
The equality operator.

Static Properties

instance TestWidgetsFlutterBinding
The current TestWidgetsFlutterBinding, if one has been created.
read-only, override

Static Methods

ensureInitialized([Map<String, String>? environment]) TestWidgetsFlutterBinding
Creates and initializes the binding. This function is idempotent; calling it a second time will just return the previously-created instance.