setTestViewForDevice function
Temporarily changes the test environment to simulate a specific device.
This is a lower-level function that snap uses internally. You typically don't need to call this directly - just use snap with device settings instead.
Returns a callback to restore the original test environment:
final restore = setTestViewForDevice(Devices.ios.iPhone16Pro);
// Test environment now simulates iPhone 16 Pro
await tester.pumpWidget(MyApp());
// Restore original test environment
restore();
The snap function handles this automatically, so prefer using snap with SnaptestSettings instead of calling this directly.
Implementation
VoidCallback setTestViewForDevice(
DeviceInfo? device,
Orientation orientation,
) {
final implicitView =
TestWidgetsFlutterBinding.instance.platformDispatcher.implicitView!;
final previousTargetPlatform = debugDefaultTargetPlatformOverride;
void restore() {
debugDefaultTargetPlatformOverride = previousTargetPlatform;
implicitView
..resetPhysicalSize()
..resetPadding()
..resetDevicePixelRatio();
}
if (device == null) {
return () {};
}
// Get screen size based on orientation
var screenSize = device.screenSize;
var safeAreas = device.safeAreas;
if (device.isLandscape(orientation)) {
// Swap width and height for landscape
screenSize = screenSize.flipped;
// Rotate safe areas for landscape (90 degrees clockwise)
// Portrait: top=notch, right=0, bottom=home, left=0
// Landscape: left=notch, top=0, right=home, bottom=0
safeAreas = device.rotatedSafeAreas!;
}
implicitView
..physicalSize = screenSize * device.pixelRatio
..padding = safeAreas.toFakeViewPadding(
devicePixelRatio: device.pixelRatio,
)
..devicePixelRatio = device.pixelRatio;
debugDefaultTargetPlatformOverride = device.identifier.platform;
return restore;
}