如何在不同的屏幕尺寸上测试Flutter小部件?

问题描述 投票:4回答:4

我有一个Flutter小部件,根据屏幕大小显示额外的数据。有没有人知道在多种不同的屏幕尺寸上测试这个小部件的方法?

我已经浏览了widget_tester源代码,但找不到任何东西。

flutter flutter-test
4个回答
9
投票

您可以使用TestWidgetsFlutterBinding指定自定义曲面大小

以下代码将运行屏幕大小为42x42的测试

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

void main() {
  final TestWidgetsFlutterBinding binding =
      TestWidgetsFlutterBinding.ensureInitialized();

  testWidgets("foo", (tester) async {
    await binding.setSurfaceSize(Size(42, 42));

    // TODO: do something
  });
}

1
投票

不知道为什么但是@rémi-rousselet的解决方案对我不起作用。我必须使用binding.window.physicalSizeTestValuebinding.window.devicePixelRatioTestValue指定屏幕大小,以便输出完全确定

我为像我这样的扑克初学者增加了一些代码。检查一下:

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.
  });
}

1
投票

@rémi-rousselet的解决方案完美无缺!

此外,如果您想测试方向更改,请尝试以下操作:

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

0
投票

虽然@RémiRousselet的回答非常有用,但并没有完全解决我的问题。事实证明,我可以将我的小部件包装在MediaQuery小部件中并设置大小。

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

void main() {
  Widget makeTestableWidget({Widget child, Size size}) {
    return MaterialApp(
      home: MediaQuery(
        data: MediaQueryData(size: size),
        child: child,
      ),
    );
  }

  testWidgets("tablet", (tester) async {
    final testableWidget = makeTestableWidget(
      child: WidgetUnderTest(),
      size: Size(1024, 768),
    );

    ...
  });

  testWidgets("phone", (tester) async {
    final testableWidget = makeTestableWidget(
      child: WidgetUnderTest(),
      size: Size(375, 812),
    );

    ...
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.