Home > other >  How to focus on conditionally rendered TextField
How to focus on conditionally rendered TextField

Time:11-26

I have a TextField that renders when a button is pressed. I am also trying to focus on this TextField but it is not working. Here is my code:

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _buttonPressed = false;
  FocusNode _focusNode = FocusNode();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ElevatedButton(
            onPressed: () {
              _buttonPressed = true;
              FocusScope.of(context).requestFocus(_focusNode);
            },
            child: Text('Button'),
          ),
          _buttonPressed
              ? TextField(
                  focusNode: _focusNode,
                )
              : Container(),
        ],
      ),
    );
  }
}

How can I focus on the TextField after the button is pressed?

CodePudding user response:

Edited your code and Tested.

Happy Coding

  • Related