Form widgets and various form-related widgets such as TextFormField, DropdownButtonFormField, etc.
This is a simple example of creating a simple form in Flutter.
Here's a simple example of using a Form widgets in Flutter:
File open lib->main.dart file −
import 'package:flutter/material.dart';
void main() {
runApp(
MyApp()
);
}
class MyApp extends StatefulWidget{
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final formGlobalKey = GlobalKey<FormState>();
// Variables to store form data
String userName = '';
String userEmail = '';
String userPassword = '';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Text('Form Example',
style:TextStyle(fontSize: 20,color: Colors.white)),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: formGlobalKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter name';
}
return null;
},
onSaved: (value) {
userName = value!;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter email';
}
return null;
},
onSaved: (value) {
userEmail = value!;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter password';
}
return null;
},
onSaved: (value) {
userPassword = value!;
},
),
SizedBox(height: 16.0),
ElevatedButton(
onPressed: () {
if (formGlobalKey.currentState!.validate()) {
formGlobalKey.currentState!.save();
print('Name: $userName, Email: $userEmail, Password: $userPassword');
}
},
child:
Container(
alignment: Alignment.center,
child: Text('Submit')),
),
],
),
),)
));
}
}
Open
Device Manager, run the emulator, and then run the application. Next,
check the working output and check the output you declared in your
code.
Output: