如何在微件层次结构中定位多个相同类型的微件? [英] How to locate multiple widget of same type in widget hierarchy?

查看:25
本文介绍了如何在微件层次结构中定位多个相同类型的微件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的一个颤动Web应用程序开发一些集成测试。我想在下面的小部件层次结构树中具体定位容器(宽度:50,高度:50),考虑到自上而下的方法。 ParentWidget-->;Row-->;Text,SizedBox,Row-->;Container(),Container(宽度:50,高度:50),Container()。 注意:没有关键方法

我尝试使用带索引的ParentWidget-->;行-->;的后代进行定位尝试选择第二个容器,但这不起作用,它失败并显示错误&;错误状态:无元素

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

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

//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);

这篇关于如何在微件层次结构中定位多个相同类型的微件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆