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();
@override
void dispose() {
_nameController.dispose();
super.dispose();
}
void _submit() {
if (_formKey.currentState!.validate()) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Hello'),
content: Text('Your name is: ${_nameController.text}'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('OK'),
),
],
),
);
}
}
@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(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller: _nameController,
decoration: InputDecoration(
labelText: 'Name',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Please enter your name';
}
return null;
},
),
SizedBox(height: 20),
Center(
child: ElevatedButton(
onPressed: _submit,
child: Text('Submit'),
),
),
],
),
),
),
);
}
}
We use a Form widget with a GlobalKey to manage validation. The TextFormField has a validator function that checks if the input is empty and returns an error message if so. The Submit button calls _formKey.currentState!.validate() to trigger validation. If valid, it shows a dialog with the entered name. We also use a TextEditingController to get the text input value.