如何在小部件层次结构中找到多个相同类型的小部件?

2024-03-27

我正在为我的一个 flutter-web 应用程序开发一些集成测试。我想考虑从上到下的方法,在下面的小部件层次结构树中专门定位容器(宽度:50,高度:50)。 ParentWidget --> 行 --> 文本、SizedBox、行 --> Container(),集装箱(宽:50,高:50), 容器()。注:不带按键方法

我尝试使用 ParentWidget --> Row --> Row --> with index 的后代进行定位尝试选择第二个容器,但这不起作用,它失败并出现错误“不良状态:无元素”.

import 'package:flutter/material.dart';

class ParentWidget extends StatelessWidget {
  const ParentWidget({Key? key});

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text("Hello World..!!"),
        SizedBox(
          width: 20,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Container(
              width: 20,
              height: 20,
              color: Colors.red,
            ),
            Container(
              width: 50,
              height: 50,
              color: Colors.red,
            ),
            Container(
              width: 20,
              height: 20,
              color: Colors.red,
            ),
          ],
        ),
      ],
    );
  }
}
final container = tester.widget<Container>(find.descendant(
    of: find.descendant(
        of: find.byType(ParentWidget), matching: find.byType(Row)),
    matching: find.descendant(
        of: find.byType(Row), matching: find.byType(Container).at(1))));

要在测试中查找多个小部件,您可以执行以下操作:

testWidgets('Test containers', (tester) async {
    
    await tester.pumpWidget(ParentWidget());

    expect(find.byType(Container), findsNWidgets(3));
  });

欲了解更多信息,请检查https://docs.flutter.dev/cookbook/testing/widget/introduction https://docs.flutter.dev/cookbook/testing/widget/introduction

编辑: 要测试第二个容器的宽度,您可以执行以下操作:

//get the second element's widget, index 1, cast it as a container and check it's width
expect((find.byType(Container).evaluate().elementAt(1).widget as Container).constraints?.maxWidth, 50.0);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在小部件层次结构中找到多个相同类型的小部件? 的相关文章

随机推荐