Home > database >  how to focus textformfield when modal closed
how to focus textformfield when modal closed

Time:08-22

I'd like to focus TextFormField, when the user close modal. but, when i press the button that close modal. the TextFormField is not focused. how can i work it? if i click button that make focus textformfield in not modal, it is work. I think I have to something in modal.

class AuthScreen extends StatefulWidget {
  const AuthScreen({Key? key}) : super(key: key);

  @override
  State<AuthScreen> createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  late FocusNode _otpFocusNode;

  @override
  void initState() {
    super.initState();
    _otpFocusNode = FocusNode();
  }

  @override
  void dispose() {
    _otpFocusNode.dispose();
    super.dispose();
  }

Future _modalBottomSheet() {
    return showMaterialModalBottomSheet(
        context: context,
        builder: (context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setModalState) {
            return SafeArea(
              child: Column(
                children: [
                  ElevatedButton(
                    onPressed: (){
Navigator.of(context).maybePop();
FocusScope.of(context).requestFocus(_otpFocusNode)} ,
                        child: Text(
                      "동의하고 진행하기"
                    ),
                  )
                ],
              ),
            );
          });
        });
  }

Widget _otpTextFormField() {
    return AnimatedOpacity(
      duration: const Duration(seconds: 1),
      opacity: _getVerification(_verificationStatus)["opacity"],
      child: TextFormField(
        focusNode: _otpFocusNode,
        enabled: _getVerification(_verificationStatus)["enabled"],
      ),
    );
  }

CodePudding user response:

I think the Widget is being rebuilt and it loses focus. You can try auto focus true if this is the only text field in the screen

Textfield(
  autoFocus : true,
)

Or add a delay to focus on it. Allowing it to complete the animation

onPressed: (){
Navigator.of(context).maybePop();
Future.delayed(Duration(seconds : 1, milliseconds: 100),(){  
  FocusScope.of(context).requestFocus(_otpFocusNode);
 }
} ,
  • Related