Form(
key
: _key
,
child
: Column(
children
: <Widget
>[
TextFormField(
controller
: _userController
,
focusNode
: _userFocusNode
,
decoration
: InputDecoration(
icon
: Icon(Icons
.person_outline
, size
: 35.0, color
: Theme
.of(context
).primaryColor
),
labelText
: '用户名'
),
validator
: (value
) {
if (value
.isEmpty
) {
return '用户名不能为空';
}
return null;
},
onSaved
: (value
) {
setState(() {
_userName
= value
;
});
},
),
SizedBox(height
: 10.0,),
TextFormField(
controller
: _passwordController
,
focusNode
: _passwordFocusNode
,
obscureText
: true,
decoration
: InputDecoration(
icon
: Icon(Icons
.lock_outline
, size
: 35.0, color
: Theme
.of(context
).primaryColor
),
labelText
: '密码'
),
onSaved
: (value
) {
setState(() {
_password
= value
;
});
},
validator
: (value
) {
if (value
.isEmpty
) {
return '密码不能为空';
}
return null;
},
),
SizedBox(height
: 40.0,),
FlatButton(
textColor
: Colors
.white
,
child
: Container(
alignment
: Alignment
.center
,
width
: width
*0.6,
height
: 40,
decoration
: BoxDecoration(
boxShadow
: [
BoxShadow(color
: Colors
.grey
,offset
: Offset(1, 1), blurRadius
: 8, spreadRadius
: -5),
BoxShadow(color
: Colors
.grey
, offset
: Offset(-1, -1), blurRadius
: 8, spreadRadius
: -5),
BoxShadow(color
: Colors
.grey
, offset
: Offset(1, -1), blurRadius
: 8, spreadRadius
: -5),
BoxShadow(color
: Colors
.grey
, offset
: Offset(-1, 1), blurRadius
: 8, spreadRadius
: -5)
],
borderRadius
: BorderRadius
.circular(40),
gradient
: LinearGradient(
colors
: [
Color(0xFF498CF7),
Color(0xFF6D7AF1)
],
begin
: Alignment
.centerLeft
,
end
: Alignment
.centerRight
)
),
child
: Text(
'登录',
style
: TextStyle(
letterSpacing
: 40.0,
fontSize
: 18.0
),
),
),
onPressed
: () {
if (_key
.currentState
.validate()) {
_key
.currentState
.save();
print(_userName
);
print(_password
);
}
},
)
],
),
)
如图上方是一个登录表单,当在输入框中输入文字后,点击空白处是无法将键盘收回的,为解决这一问题可以在Form外面包裹一层GestureDetector,并在onTap中调用FocusScope.of(context).requestFocus(blankNode)方法即可。
FocusNode blankNode
= FocusNode();
...
Widget
build () {
reutrn
GestureDetector(
onTap
: () {
FocusScope
.of(context
).requestFocus(blankNode
);
},
...
);
}
如果当输入完用户名后,要求焦点自动跳至密码框,则可以在用户名输入框的onEditingComplete事件中调用FocusScope.of(context).requestFocus(_passwordFocusNode);。 修改后的效果如下: