我正在使用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
],
),
)
);
},
),
);
}
}
这不是将焦点设置在第二个字段中。但是,如果我关闭对话框并再次打开它,则会聚焦第二个字段。
任何人都可以帮我吗?
答案 0 :(得分:0)
这是因为您的AlertDialog
需要位于自己的 StatefulWidget
中。您当前的代码显示,您的state
,TextField
和AlertDialog
是MainScreen
类的一部分,这意味着必须首先在MainScreen
中进行任何更新上下文,而您需要的是让所有更新都发生在AlertDialog
上下文中。
TL; DR:使用AlertDialog
和StatefulWidget
将您的TextField
重构为自己的FocusNode
。