【问题标题】:Flutter Test Widgets find.byType(TextField) Works, find.byWidget(TextField()) Doesn't work. Why?Flutter 测试小部件 find.byType(TextField) 有效,find.byWidget(TextField()) 无效。为什么?
【发布时间】:2025-12-15 01:15:01
【问题描述】:

我刚刚开始使用颤振小部件测试并遇到了这个问题。我想知道这是否是预期的行为。 当尝试使用 find.byType 找到我的 TextField 时,它会成功,但使用 find.byWidget 却不会。这是正常的还是我做错了什么?目标是稍后在文本字段中输入文本,然后点击按钮。

我的文本框和按钮:

Column(
    children: [
      TextField(
        style: TextStyle(
          color: Colors.black,
        ),
        autofocus: true,
        autocorrect: false,
        enableSuggestions: false,
        controller: _controller,
        cursorColor: Colors.black,
        decoration: InputDecoration(
            hintText: 'Fill in.....',
          hintStyle: TextStyle(fontSize: 18),
        ),
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          ElevatedButton(
              onPressed: () {
                onSubmit(_controller.text);
              },
              child: Text('Press me!',
                  style: TextStyle(
                    fontSize: 18,
                    color: Theme.of(context).primaryColorBrightness ==
                        Brightness.dark
                        ? Colors.white
                        : Colors.black,
                  ))),
      ],),
    ],
  ),

这是我的测试:

tester.ensureVisible(find.byType(TextInputWidget));
  expect(find.byType(TextInputWidget), findsOneWidget);

  final a = TextField(
    style: TextStyle(
      color: Colors.black,
    ),
    autofocus: true,
    autocorrect: false,
    enableSuggestions: false,
    controller: TextEditingController(),
    cursorColor: Colors.black,
    decoration: InputDecoration(
      hintText: 'Fill in.....',
      hintStyle: TextStyle(fontSize: 18),
    ),
  );

  //expect(find.byWidget(a), findsOneWidget); // Fails
  expect(find.byType(TextField), findsOneWidget); //Succeeds

【问题讨论】:

    标签: flutter widget widget-test-flutter


    【解决方案1】:

    您的部分测试丢失,但您似乎正试图在测试器中找到未知的小部件a。 如果您想通过变量引用来查找小部件,则必须在定义小部件时使用相同的引用,然后将其传递给pumpWidget() 方法,如下所示:

    final a = TextField(...);
    tester.pumpWidget(Container(
      child: a,
    ));
    expect(find.byWidget(a), findsOneWidget);
    

    【讨论】:

    • 我不再使用这个项目,所以我无法测试它。不过谢谢你的回答。