Flutter Form Get Values
When working with forms in Flutter, you can utilize the Form
widget to create a collection of form fields and access their values. Here’s an example:
{% raw %}
import 'package:flutter/material.dart';
class MyForm extends StatefulWidget {
@override
_MyFormState createState() => _MyFormState();
}
class _MyFormState extends State {
final _formKey = GlobalKey();
String _name = '';
String _email = '';
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
validator: (value) {
if (value.isEmpty) {
return 'Please enter your name';
}
return null;
},
onSaved: (value) {
_name = value;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (value.isEmpty) {
return 'Please enter your email';
}
return null;
},
onSaved: (value) {
_email = value;
},
),
RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
print('Name: $_name');
print('Email: $_email');
}
},
child: Text('Submit'),
),
],
),
);
}
}
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Form'),
),
body: Center(
child: MyForm(),
),
),
));
}
{% endraw %}
In this example, we create a Form
widget using the _formKey
global key to manage the form’s state. Inside the form, we have two TextFormField
s for capturing the user’s name and email. Both fields have a validation function specified in the validator
property, which checks if the fields are empty. The onSaved
property is responsible for saving the field value to the respective variables (_name
and _email
).
Finally, we have a RaisedButton
that triggers the form validation and saves the field values when pressed. If the form passes validation, the print
function outputs the name and email values.
Remember to include the necessary dependencies in your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
- Flutter floating action button position fixed
- Flutter failed to delete a directory at “build”. the flutter tool cannot access the file or directory. please ensure that the sdk and/or project is installed in a location that has read/write permissions for the current user.
- Flutter firebase send notification to specific user
- Flutter firebase messaging onbackgroundmessage not working
- Flutter firebase datetime
- Flutter finished with non-zero exit value 1
- Flutter execution failed for task ‘:app:checkdebugaarmetadata’.
- Flutter form clear validation