[英]Flutter check if TextField has focus
我想知道如何断言特定的 TextField 是否具有焦点。 以下代码失败,因为它说focusNode
是null
。 (我无法编辑小部件代码本身)
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);
})
如文档中所述,首先您需要创建 FocusNode 的实例,然后将其添加到 TextField。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.