Joel Castro
Joel Castro

Reputation: 467

How to focus on conditionally rendered TextField

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?

Upvotes: 0

Views: 30

Answers (1)

Ska Lee
Ska Lee

Reputation: 46

Edited your code and Tested.

Happy Coding 😀

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

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

class _MyHomePageState extends State<MyHomePage> {
  var _buttonPressed = false;
  late final FocusNode _focusNode;
  late final TextField textFieldWidget;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    textFieldWidget = TextField(
      autofocus: true,
      focusNode: _focusNode,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ElevatedButton(
            onPressed: () => setState(() => _buttonPressed = true),
            child: const Text('Button'),
          ),
          _buttonPressed ? textFieldWidget : Container()
        ],
      ),
    );
  }
}

Upvotes: 1

Related Questions