简体   繁体   中英

How to listen to a FocusNode with GetX in Flutter

I've just discovered GetX and I love it? Is there a neat way of listening to a FocusNode with GetX instead of using a StatefulWidget?

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,
      ),
    );
  }
}

you can create a StatelessWidget or a GetView<MyController> and add the focus node in the controller

class MyController extends GetXController {
   final FocusNode focusNode = FocusNode();
   
   @override
   void onInit() {
        focusNode.addListener((){ ...do some stuff }));
        super.onInit();
   }

   @override
   onClose() {
     focusNode.dispose();
     super.onClose();
   }
}

Then you can use this in your widget

...     
  @override
  Widget build(BuildContext context) {
    return CustomContainer(
      isFocused: controller.focusNode.hasFocus,
      child: TextField(
        focusNode: controller.focusNode.focusNode,
      ),
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM