How to test Flutter widgets on different screen sizes?

I have a Flutter widget which shows extra data depending on the screen size. Does anyone know a way of testing this widget on multiple different screen sizes?

I've had a look through the widget_tester source code but can't find anything.


You can specify custom surface size by using WidgetTester

The following code will run a test with a screen size of 42x42

import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets("foo", (tester) async {
    tester.binding.window.physicalSizeTestValue = Size(42, 42);

    // resets the screen to its original size after the test end
    addTearDown(tester.binding.window.clearPhysicalSizeTestValue);

    // TODO: do something
  });
}

Not sure why but solution of @rémi-rousselet didn't work for me. I've had to specify screen size using binding.window.physicalSizeTestValue and binding.window.devicePixelRatioTestValue so that output is fully deterministic

I've added a little bit more code for flutter beginners like me. Check this:

void main() {

  final TestWidgetsFlutterBinding binding =
    TestWidgetsFlutterBinding.ensureInitialized();

  testWidgets("Basic layout test (mobile device)", (tester) async {
    binding.window.physicalSizeTestValue = Size(400, 200);
    binding.window.devicePixelRatioTestValue = 1.0;

    await tester.pumpWidget(new MyApp());

    expect(find.byType(MyHomePage), findsOneWidget);
    // etc.
  });
}

There is a package called device_preview that can simulate your flutter app running on different devices.


@rémi-rousselet's solution works perfectly!

In addition if you want to test an orientation change, try this:

const double PORTRAIT_WIDTH = 400.0;
const double PORTRAIT_HEIGHT = 800.0;
const double LANDSCAPE_WIDTH = PORTRAIT_HEIGHT;
const double LANDSCAPE_HEIGHT = PORTRAIT_WIDTH;

final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();

await binding.setSurfaceSize(Size(PORTRAIT_WIDTH, PORTRAIT_HEIGHT));
await tester.pumpWidget(MyWidget());

// test in portrait

await binding.setSurfaceSize(Size(LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT));
await tester.pumpAndSettle();

// OrientationBuilder gets triggered

// test in landscape