我希望向我的应用程序添加验证,但是我不知道要保存TextFormField中的数据并将其分配给_email和_password。我对使用Flutter进行编码非常陌生...。或根本不进行编码,非常感谢您的帮助。
任何人都可以给我一些建议,以使数据得到验证吗?
到目前为止,这里是我所拥有的,但是我无法从TextFormFields中获取任何数据到分配的String值中以用于验证。
import 'package:flutter/material.dart';
import 'package:ursussupport/home_page.dart';
class LoginPage extends StatefulWidget {
static String tag = 'login-page';
@override
_LoginPageState createState() => new _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final scaffoldKey = GlobalKey<ScaffoldState>();
final formKey = GlobalKey<FormState>();
String _email;
String _password;
void _onSubmit() {
final form = formKey.currentState;
if (form.validate()) {
form.save();
// Email & password matched our validation rules
// and are saved to _email and _password fields.
_performLogin();
}
}
void _performLogin(){
Navigator.of(context).pushNamed(HomePage.tag);
}
@override
Widget build(BuildContext context) {
final logo = Hero(
tag: 'avatar',
child: CircleAvatar(
backgroundColor: Colors.transparent,
radius: 90.0,
child: Image.asset('assets/niishaw2.jpg'),
),
);
final email = TextFormField(
keyboardType: TextInputType.emailAddress,
autofocus: false,
decoration: InputDecoration(
hintText: 'Enter Email',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
labelText: null,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(32.0)
)
),
);
final password = TextFormField(
autofocus: false,
obscureText: true,
decoration: InputDecoration(
hintText: 'Enter Password',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(32.0)
)
),
);
final loginButton = Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Material(
borderRadius: BorderRadius.circular(30.0),
shadowColor: Colors.lightBlueAccent.shade100,
elevation: 5.0,
child: MaterialButton(
minWidth: 200.0,
height: 42.0,
onPressed: _performLogin,
color: Colors.lightBlueAccent,
child: Text('Login', style: TextStyle(color: Colors.white)),
)
),
);
final forgotLabel = FlatButton(
child: Text(
'Forgot Password?',
style: TextStyle(color: Colors.black54),
),
onPressed: (){
},
);
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.only(left: 24.0, right: 24.0),
children: <Widget>[
logo,
SizedBox(height: 50.0),
email,
SizedBox(height: 8.0),
password,
SizedBox(height: 24.0),
loginButton,
forgotLabel
],
) ,
),
);
}
}
答案 0 :(得分:1)
您可以使用TextField,它具有onChanged属性,因此您可以执行此操作,并且将非常适合您。 使用此代码示例
final email = TextField(
keyboardType: TextInputType.emailAddress,
autofocus: false,
decoration: InputDecoration(
hintText: 'Enter Email',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
labelText: null,
),
onChanged: (String str){
setState((){
email = str;
});
},
);
您可以在代码中简单地添加上面显示的 onChanged 属性。