简体   繁体   English

Flutter 小部件测试:未应用 MediaQuery 设置填充

[英]Flutter widget test: setting padding with MediaQuery not applied

Since flutter's testing environment does not contain system status bar like the emulator, I would like to add padding at the top using MediaQuery .由于 Flutter 的测试环境不包含像模拟器这样的系统状态栏,我想使用MediaQuery在顶部添加填充。

Here's my testing code:这是我的测试代码:

void main() {
  testWidgets('MediaQuery padding test', (WidgetTester tester) async {
    const double statusBarHeight = 24.0;

    await tester.pumpWidget(
      MaterialApp(
        home: MediaQuery(
          data: const MediaQueryData(
            viewInsets: EdgeInsets.only(top: statusBarHeight),
          ),
          child: Scaffold(
            appBar: AppBar(
              title: const Text('PopupMenu Test'),
            ),
              
          ),
        ),
      ),
    );

    expect(find.byType(AppBar), findsOneWidget);
    expect(tester.getTopLeft(find.byType(AppBar)).dy, windowPaddingTop);
  });
}

Since I added 24.0 of top padding using MediaQueryData.viewInsets , I expected the AppBar top left y axis is 24.0 , but the result is zero.由于我使用MediaQueryData.viewInsets添加了24.0的顶部填充,我预计 AppBar 左上 y 轴为24.0 ,但结果为零。
I have also tried testing with viewPadding instead of viewInsets , but it has produced the same result.我也尝试使用viewPadding而不是viewInsets进行测试,但它产生了相同的结果。

I want to know the reason why top padding is not applied in my test, and how to solve this problem.我想知道我的测试中没有应用顶部填充的原因,以及如何解决这个问题。 I would appreciate any help.我将不胜感激任何帮助。 Thanks.谢谢。

Old answer:老答案:
[You are not supposed to use MediaQuery and Scaffold this way. [您不应该以这种方式使用 MediaQuery 和 Scaffold。 MediaQuery should not be inside the widget tree and, use it to retrieve media data. MediaQuery 不应位于小部件树内,并使用它来检索媒体数据。 Scaffold should cover the entire screen]脚手架应覆盖整个屏幕]

Updating(based on the answer in the comments):更新(基于评论中的答案):

They are using MediaQuery to simulate non-safe area, like the notch in some mobile.他们正在使用MediaQuery来模拟非安全区域,例如某些移动设备中的缺口。 This is used only to teste the scaffold widget against invading the safe are (like the notch).这仅用于测试脚手架小部件以防止入侵安全区域(如缺口)。

If you just want to test, the error is here:如果你只是想测试,错误在这里:

viewInsets: EdgeInsets.only(top: statusBarHeight),

It should be viewPadding intead of viewInsets:它应该是 viewPadding 而不是 viewInsets:

viewPadding: EdgeInsets.only(bottom: viewPadding),

Now if you are trying to build a screen instead of test one, you don't need (and shall not) to use MediaQuery.现在,如果您尝试构建屏幕而不是测试屏幕,则不需要(也不应该)使用 MediaQuery。 Just use your Scaffold as the root widget.只需使用您的 Scaffold 作为根小部件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM