通过使用FocusNode类,您可以添加焦点侦听器并可以捕获焦点变化。
通过使用Focus类,您只需包装 TextField 并添加一个 onFocusChange 参数。
[解决方案 1]
FocusNode focusNode = FocusNode();
- 在 initState 处添加 FocusNode 的侦听器。
focusNode.addListener(() {
print('1: ${focusNode.hasFocus}');
});
- 将 FocusNode 实例添加到 TextField 的 focusNode 参数。
TextField(
focusNode: focusNode,
)
[解决方案 2]
Focus(
child: TextField(),
onFocusChange: (hasFocus) {
print('2: $hasFocus');
},
)
[示例完整代码]
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
FocusNode focusNode = FocusNode();
@override
void initState() {
super.initState();
focusNode.addListener(() {
print(focusNode.hasFocus);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _buildBody(),
);
}
Widget _buildBody() {
return TextField(
focusNode: focusNode,
);
}
}