Flutter : Using Form and Text Fields


Flutter is a popular cross-platform mobile development framework that allows developers to build native apps for both Android and iOS using a single codebase.

Today we will see how to use form and textfields.

One of the key components in Flutter is the form and TextFormField, which can be used to build user input forms in your app.

To use form and TextFormField in Flutter, you need to import the form package and wrap your form widgets in a Form widget. Inside the Form widget, you can use the TextFormField widget to create input fields for user input.

To create a form with a single text input field, we can use the following code:

import 'package:flutter/material.dart';
import 'package:form/form.dart';
class MyForm extends StatefulWidget {
@override
_MyFormState createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
final _formKey = GlobalKey<FormState>();
String _inputText;
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Enter your name'),
validator: (value) {
if (value.isEmpty) {
return 'Please enter your name';
}
return null;
},
onSaved: (value) => _inputText = value,
),
RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Hello, $_inputText!'))
);
}
},
child: Text('Submit'),
),
],
),
);
}
}
view raw FlutterForm hosted with ❤ by GitHub


In the code above, we create a Form widget with a TextFormField and a RaisedButton. The TextFormField has a decoration property to customize the appearance of the input field, and a validator function to check the user input. The onSaved function is called when the form is submitted, and it saves the user input to a variable.

The RaisedButton has an onPressed function that calls the validate and save methods on the FormState object to validate and save the user input. If the form is valid, it shows a snackbar with the user input.

We can add more input fields to the form by adding more TextFormField widgets inside the Column widget. You can also customize the appearance of the form and the input fields using the various properties and styles available in Flutter.

In short using form and TextFormField in Flutter is a simple and powerful way to build user input forms in your app. With a few lines of code, you can create a form with multiple input fields and validate and save the user input.

Thanks for the reading...




Flutter : Using Form and Text Fields

Flutter is a popular cross-platform mobile development framework that allows developers to build native apps for both Android and iOS using ...