Form validation and form submission are two things that the form widget helps to implement. For an application to be easy and safe, it is important to check if the information the user provides is valid. If the user happens to fill out the form correctly, the information, the widget displays an error message that is user-friendly to let the users know what exactly happened.
The use of the Form widget with validation in flutter
import 'package:flutter/material.dart';
void main(){
runApp(MyWidget());
}
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final _formkey = GlobalKey<FormState>();
final _name = TextEditingController();
final _username = TextEditingController(); @override Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Simple Form Example')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formkey,
child: Column(
children: [
TextFormField(
controller: _name,
decoration: InputDecoration(labelText: 'Enter your name'),
validator: (value){
if(value == null || value.isEmpty){
return 'Please enter your name';
}
return null;
},
),
TextFormField(
controller: _username,
decoration: InputDecoration(labelText: 'Enter your username'),
validator: (value){
if(value == null || value.isEmpty){
return 'Please enter your username';
}
return null;
},
),
SizedBox(height: 20.0,),
ElevatedButton(
onPressed: (){
if(_formkey.currentState?.validate() == true){
print('form is being submitted');
}
},
child: Text('Submit')
)
],
)
)
),
),
);
}
}
How to Validate Forms in Flutter | Form Widget Tutorial
FlutterFormForm WidgetForm widget in flutterflutter form widgetflutter form validationflutter formhow to validate formflutter form keyvalidation in flutterflutter form fields
Conversation
Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!
Join the discussion and share your insights now!
Comments 0