gpt4 book ai didi

flutter - 如何在小部件层次结构中定位多个相同类型的小部件?

转载 作者:行者123 更新时间:2023-12-05 05:47:09 25 4
gpt4 key购买 nike

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

我尝试使用 ParentWidget 的后代 --> Row --> Row --> 和索引来定位,试图选择第二个容器,但这不起作用,它失败并显示错误 "Bad state: No元素”

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

编辑:要测试第二个 Container 的宽度,您可以这样做:

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

关于flutter - 如何在小部件层次结构中定位多个相同类型的小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71049030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com