Developing Flutter apps means they should look good and work correctly on all sorts of devices.
Prevent Overflows for the Screen Sizes
One big challenge is making sure your layouts don't break or overflow on different screen sizes and densities. Widget tests are great for checking this automatically.
How it Works
You can set up your widget tests to run the same test logic but with different screen configurations. This way, you can catch layout issues early for phones, tablets, or even custom sizes you define.
This approach lets you run a test with every screen setup you list.
Defining Screen Sizes
First, you can create a simple class to hold screen details like name, width, height, and pixel density.
class ScreenSize {
final String name;
final double width;
final double height;
final double pixelDensity;
const ScreenSize(this.name, this.width, this.height, this.pixelDensity);
String toString() => name;
}
const iphone8Plus = ScreenSize('iPhone 8 Plus', 414, 736, 3);
const iphone11Max = ScreenSize('iPhone 11 Max', 414, 896, 3);
const samsungGalaxyS = ScreenSize('Android Samsung Galaxy S', 480, 800, 1);
final basicPhones = <ScreenSize>[iphone8Plus, iphone11Max];
Testing with Multiple Sizes
You can use ValueVariant
in your testWidgets
function along with a helper to set the screen size before testing your widget.
extension ScreenSizeManager on WidgetTester {
Future<void> setScreenSize(ScreenSize screenSize) async {
return _setScreenSize(
width: screenSize.width,
height: screenSize.height,
pixelDensity: screenSize.pixelDensity,
);
}
}
testWidgets(
'click on button => shows an anchored widget overlay',
(WidgetTester tester) async {
await tester.setScreenSize(screenSizeVariants.currentValue!); // Set the current screen size
await tester.pumpWidget(const MyAppWithCircleAnchored());
expect(find.byType(AnchoredHelper), findsNothing);
await tester.tap(find.byType(OutlinedButton).first);
await tester.pump(const Duration(seconds: 2));
expect(find.byType(AnchoredHelper), findsOneWidget);
},
variant: ValueVariant<ScreenSize>(basicPhones), // Run the test for each screen in the list
);
Results
The test runner will show that your test is run for each screen size defined in your basicPhones
list, giving you confidence that your UI holds up across common devices.