1

I would like to know how to assert if a specific TextField has focus or not. The following code fails because it is saying focusNode is null. ( I cannot edit the Widget code itself )

    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
  • same issue here, have you found a solution? Commented Dec 3, 2021 at 20:32

1 Answer 1

1

As described in the documentation first you need to create an instance of the FocusNode and then add it to TextField.

Sign up to request clarification or add additional context in comments.

1 Comment

I can try, but you can follow the link, it has nice explanation with example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.