如何在 Flutter 中使用 GetX 监听 FocusNode
How to listen to a FocusNode with GetX in Flutter
我刚刚发现 GetX,我喜欢它!有没有一种使用 GetX 而不是使用 StatefulWidget 来收听 FocusNode 的巧妙方法?
class CustomTextField extends StatefulWidget {
const CustomTextField({Key? key}) : super(key: key);
@override
_CustomTextFieldState createState() => _CustomTextFieldState();
}
class _CustomTextFieldState extends State<CustomTextField> {
final FocusNode _focusNode = FocusNode();
@override
void initState() {
_focusNode.addListener(() => setState(() {}));
super.initState();
}
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return CustomContainer(
isFocused: _focusNode.hasFocus,
child: TextField(
focusNode: _focusNode,
),
);
}
}
您可以创建一个 StatelessWidget
或 GetView<MyController>
并在控制器中添加焦点节点
class MyController extends GetXController {
final FocusNode focusNode = FocusNode();
@override
void onInit() {
focusNode.addListener((){ ...do some stuff }));
super.onInit();
}
@override
onClose() {
focusNode.dispose();
super.onClose();
}
}
然后您可以在您的小部件中使用它
...
@override
Widget build(BuildContext context) {
return CustomContainer(
isFocused: controller.focusNode.hasFocus,
child: TextField(
focusNode: controller.focusNode.focusNode,
),
);
}
我刚刚发现 GetX,我喜欢它!有没有一种使用 GetX 而不是使用 StatefulWidget 来收听 FocusNode 的巧妙方法?
class CustomTextField extends StatefulWidget {
const CustomTextField({Key? key}) : super(key: key);
@override
_CustomTextFieldState createState() => _CustomTextFieldState();
}
class _CustomTextFieldState extends State<CustomTextField> {
final FocusNode _focusNode = FocusNode();
@override
void initState() {
_focusNode.addListener(() => setState(() {}));
super.initState();
}
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return CustomContainer(
isFocused: _focusNode.hasFocus,
child: TextField(
focusNode: _focusNode,
),
);
}
}
您可以创建一个 StatelessWidget
或 GetView<MyController>
并在控制器中添加焦点节点
class MyController extends GetXController {
final FocusNode focusNode = FocusNode();
@override
void onInit() {
focusNode.addListener((){ ...do some stuff }));
super.onInit();
}
@override
onClose() {
focusNode.dispose();
super.onClose();
}
}
然后您可以在您的小部件中使用它
...
@override
Widget build(BuildContext context) {
return CustomContainer(
isFocused: controller.focusNode.hasFocus,
child: TextField(
focusNode: controller.focusNode.focusNode,
),
);
}