TextFormField focuses automatically when a DatePicker dialog is closed

157 views Asked by At

I am filling the TextFormField form a Date Picker using showDatePicker method which is called when the TextFormField got focus. The focus change in the TextFormField is identified using the focus node.

class MyWidget extends StatefulWidget {
  const MyWidget({super.key});

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final FocusNode _focusNode = FocusNode();
  final TextEditingController _textEditingController = TextEditingController();

  @override
  void initState() {
    _focusNode.addListener(() async {
      if (_focusNode.hasFocus) {
        DateTime? selectedDate = await showDatePicker(
            useRootNavigator: false,
            context: context,
            initialDate: DateTime.now(),
            firstDate: DateTime(2000),
            lastDate: DateTime(2100));

        if (selectedDate != null) {
          _textEditingController.text = selectedDate.toLocal().toString();
        }
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: _textEditingController,
      focusNode: _focusNode,
    );
  }
}

After the Date picker is closed the TextFormField got focus once again and the date picker is showed once again, and the application is unusable. How to prevent focusing of the text form field once the date picker is closed?

1

There are 1 answers

0
Nidhi Jain On BEST ANSWER

You have to unfocus the text field to stop date picker opening again and again.

Replace

if (selectedDate != null) {
   _textEditingController.text = selectedDate.toLocal().toString();
}

With

if (selectedDate != null) {
   _textEditingController.text = selectedDate.toLocal().toString();
   FocusManager.instance.primaryFocus?.unfocus();
}