所以我想为我的应用程序创建一个注册页面。到目前为止,我已经得到了一些欢迎文本和一个输入表单,用户可以在其中输入他们的电子邮件。我也有一个按钮,这将最终改变页面下面的输入字段,说'下一步'。这个想法是让按钮被禁用,这很简单,但当用户输入至少一个字符,然后是'@',然后是'.com,.co.uk等的字符串列表)下一个按钮将成为启用。我试图添加一个验证if else语句的形式,但没有喜悦,所以从下面的代码中删除了它。我想我要问的是我如何:
- 验证输入是否符合我的要求
- 如果没有,则禁用该按钮
- 启用按钮
非常感谢对上述任何内容的所有回复/贡献!
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() {
runApp(MyApp());
}
class MyCustomForm extends StatefulWidget {
@override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
class MyCustomFormState extends State<MyCustomForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Enter your email'),
),
]),
);
}
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test Bench',
home: Stack(
children: [
Scaffold(
body: Container(
width: double.infinity,
decoration: BoxDecoration(color: Colors.pinkAccent),
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(
children: [
Text(
"Hello, Let's Get Started...n",
style: TextStyle(
fontSize: 60.0,
fontWeight: FontWeight.bold,
fontFamily: 'Oswald',
color: Colors.black,
),
),
MyCustomForm(),
ButtonTheme(
minWidth: 250.0,
child: RaisedButton(
onPressed: null,
child: Text("Next"),
),
),
],
),
),
),
),
],
),
);
}
}
这是一个可能的解决方案。我使用regex来验证输入的电子邮件。你可以从这里了解更多关于验证的信息:https://flutter.dev/docs/cookbook/forms/validation
class MyApp extends StatefulWidget {
// This widget is the root of your application.
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _formKey = GlobalKey<FormState>();
bool isValidated = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test Bench',
home: Stack(children: [
Scaffold(
body: Container(
width: double.infinity,
decoration: BoxDecoration(color: Colors.pinkAccent),
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(children: [
Text("Hello, Let's Get Started...n",
style: TextStyle(
fontSize: 60.0,
fontWeight: FontWeight.bold,
fontFamily: 'Oswald',
color: Colors.black,
)),
Form(
key: _formKey,
child: Column(children: <Widget>[
TextFormField(
onChanged: (input) {
_formKey.currentState.validate();
},
validator: (input) {
var regex = RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+.[a-zA-Z]+");
if (!regex.hasMatch(input) && isValidated) {
setState(() {
isValidated = false;
});
return null;
} else {
setState(() {
isValidated = true;
});
return input;
}
},
decoration: InputDecoration(
labelText: 'Enter your email'),
),
])),
ButtonTheme(
minWidth: 250.0,
child: RaisedButton(
onPressed:
isValidated ? () => print('Signed In') : null,
child: Text("Next"),
),
),
]))))
]));
}
}