Flutter - 将焦点设置为onFieldSubmitted中的另一个TextFormField

时间:2018-04-09 21:08:13

标签: dart flutter

我正在使用AlertDialog中的后续TextFormFields,其中输入的提交应该将焦点设置在下一个输入上。我目前正在尝试使用以下代码实现此目的:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MainScreen()
    );
  }
}

class MainScreen extends StatefulWidget {
  @override
  _MainScreenState createState() => new _MainScreenState(); 
}

class _MainScreenState extends State<MainScreen> {
  final TextEditingController _firstFieldController = new TextEditingController();
  final TextEditingController _secondFieldController = new TextEditingController();
  FocusNode _focusNode ;

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

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }
  @override 
  Widget build(BuildContext context) {
    var firstField = new TextFormField(
      controller: _firstFieldController,
      keyboardType: TextInputType.phone,
      decoration: new InputDecoration(
        labelText: 'First field',
        contentPadding: new EdgeInsets.fromLTRB(.0, 8.0, .0, 4.0),
        counterText: ' '
      ),
      onFieldSubmitted: (String textInput) {
        FocusScope.of(context).requestFocus(_focusNode);
      },           
    );

    var secondField = new TextFormField(
      focusNode: _focusNode,
      controller: _secondFieldController,
      keyboardType: TextInputType.phone,
      decoration: new InputDecoration(
        labelText: 'Second field',
        contentPadding: new EdgeInsets.fromLTRB(.0, 8.0, .0, 4.0),
        counterText: ' '
      ),
    );

    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Main'),
      ),
      body: new Center(
        child: new Text('Hello from the main screen!'),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.add),
        onPressed: () {
          showDialog(
            context: context,
            child: new AlertDialog(
              title: new Text('Form'),
              content: new Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new Container(
                    margin: new EdgeInsets.only(bottom: 4.0),
                    child: firstField
                  ),
                  secondField
                ],
              ),
            )
          );
        },
      ),
    );
  }
}

这不是将焦点设置在第二个字段中。但是,如果我关闭对话框并再次打开它,则会聚焦第二个字段。

任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:0)

这是因为您的AlertDialog需要位于自己的 StatefulWidget中。您当前的代码显示,您的stateTextFieldAlertDialogMainScreen类的一部分,这意味着必须首先在MainScreen中进行任何更新上下文,而您需要的是让所有更新都发生在AlertDialog上下文中。

TL; DR:使用AlertDialogStatefulWidget将您的TextField重构为自己的FocusNode