Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created March 27, 2025 18:43
Show Gist options
  • Save prof3ssorSt3v3/44d6bd175c109160f64d7bf053f82e5b to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/44d6bd175c109160f64d7bf053f82e5b to your computer and use it in GitHub Desktop.
Flutter example of a form with two TextFormField widgets that get validated when clicking the submit button
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: LoginPage(),
));
}
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final _formKey = GlobalKey<FormState>(); // Form key for validation
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
void _submitForm() {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Form is valid!")),
);
}
}
String? _validateField(String? value) {
if (value == null || value.length < 8) {
return "Must be at least 8 characters long";
}
return null;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Login Page")),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: _emailController,
decoration: InputDecoration(labelText: "Email"),
validator: _validateField,
),
SizedBox(height: 10),
TextFormField(
controller: _passwordController,
decoration: InputDecoration(labelText: "Password"),
obscureText: true,
validator: _validateField,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _submitForm,
child: Text("Submit"),
),
],
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment