颤振检查TextField是否具有焦点

时间:2020-06-08 05:08:42

标签: flutter dart

我想知道如何断言特定TextField是否具有焦点。 以下代码失败,因为它说focusNodenull。 (我无法编辑Widget代码本身)

    final fooKey = Key('foo');
    final barKey = Key('bar');
    final namePage = MediaQuery(
      data: MediaQueryData(),
      child: MaterialApp(
        home: Scaffold(
          body: Column(
            children: <Widget>[
              TextField(
                key: fooKey,
                autofocus: true,
              ),
              TextField(
                key: barKey,
              ),
            ],
          ),
        ),
      ),
    );
    testWidgets('Should focus on fooTextField not barTextField', (WidgetTester tester) async {
      await tester.pumpWidget(namePage);
      expect(tester.testTextInput.isVisible, true);
      final fooField = find.byKey(fooKey).evaluate().single.widget as TextField;
      final barField = find.byKey(barKey).evaluate().single.widget as TextField;
      await tester.enterText(find.byKey(fooKey), 'I am a foo');
      expect(fooField.focusNode.hasFocus, true);
      expect(barField.focusNode.hasFocus, false);
    })

1 个答案:

答案 0 :(得分:0)

documentation中所述,首先需要创建FocusNode的实例,然后将其添加到TextField。