Reputation: 2147
I'm building a sign-in screen with 2 inputs. I want to verify the email address when the button is pressed. My guess is I have to let the view know the value has been changed.
Button
RaisedButton(
color: Colors.blue,
textColor: Colors.white,
child: Text('Login'),
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(4)),
onPressed: () {
print('hey');
if (!EmailValidator.validate(_emailController.text)) {
_emailValid = false;
return;
}
// do login stuffs
},
)
Text Field
_textFieldWidget('Email', false, _emailController, TextInputType.emailAddress, _emailValid ? 'not valid' : null)
Widget _textFieldWidget(String label, bool obscureText,
TextEditingController controller, TextInputType type, String errorText) {
return new TextField(
obscureText: obscureText,
controller: controller,
keyboardType: type,
decoration: InputDecoration(
border: OutlineInputBorder(), labelText: label, errorText: errorText),
);
}
Upvotes: 3
Views: 22894
Reputation: 618
If you want to validate user input you should check out Form's and Validator's. In a Form you can spedify a TextFormField with a validator - here is an example taken from the flutter website:
// Create a Form widget.
class MyCustomForm extends StatefulWidget {
@override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
// Create a global key that uniquely identifies the Form widget
// and allows validation of the form.
//
// Note: This is a GlobalKey<FormState>,
// not a GlobalKey<MyCustomFormState>.
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
onPressed: () {
// Validate returns true if the form is valid, or false
// otherwise.
if (_formKey.currentState.validate()) {
// If the form is valid, display a Snackbar.
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Processing Data')));
}
},
child: Text('Submit'),
),
),
],
),
);
}
}
For further informationen check out the flutter website https://flutter.dev/docs/cookbook/forms/validation
Upvotes: 3