import 'package:flutter/material.dart';
class SimpleFormScreen extends StatefulWidget {
@override
State<SimpleFormScreen> createState() => _SimpleFormScreenState();
}
class _SimpleFormScreenState extends State<SimpleFormScreen> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
final _emailController = TextEditingController();
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
super.dispose();
}
void _submitForm() {
if (_formKey.currentState?.validate() ?? false) {
final name = _nameController.text.trim();
final email = _emailController.text.trim();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Form submitted: $name, $email')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Simple Form Screen')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _nameController,
decoration: InputDecoration(labelText: 'Name'),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Please enter your name';
}
return null;
},
),
SizedBox(height: 16),
TextFormField(
controller: _emailController,
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Please enter your email';
}
return null;
},
),
SizedBox(height: 32),
ElevatedButton(
onPressed: _submitForm,
child: Text('Submit'),
),
],
),
),
),
);
}
}This solution uses a Form widget with a GlobalKey to manage the form state and validation.
Each TextFormField has a validator that checks if the input is empty and returns an error message if so.
The _submitForm method calls validate() on the form state. If validation passes, it shows a SnackBar with the entered name and email.
This approach keeps the UI responsive and provides immediate feedback to the user.