flutter 如何关注有条件呈现的TextField

5q4ezhmt  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(112)

我有一个TextField,当一个按钮被按下时,它会呈现。我也试图关注这个TextField,但是它不工作。下面是我的代码:

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

如何在按下按钮后将焦点放在TextField上?

lmvvr0a8

lmvvr0a81#

已编辑代码并已测试。
快乐编码😀

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

相关问题