Forms and POST Requests
When you need to send user-generated data to a backend, you often use a form in your Flutter app. Forms let users enter information, such as their name or email, which you then collect and send to an API. To send this data, you typically use a POST request, which creates or updates data on the server. Before sending, it is important to validate the input to ensure that only correct and expected data is transmitted. This prevents unnecessary errors and improves your appβs reliability.
main.dart
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; void main() => runApp(FormPostDemo()); class FormPostDemo extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: UserFormPage(), ); } } class UserFormPage extends StatefulWidget { @override _UserFormPageState createState() => _UserFormPageState(); } class _UserFormPageState extends State<UserFormPage> { final _formKey = GlobalKey<FormState>(); String _name = ''; String _email = ''; String? _errorMessage; bool _isSubmitting = false; Future<void> _submitForm() async { setState(() { _errorMessage = null; _isSubmitting = true; }); if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); final response = await http.post( Uri.parse('https://jsonplaceholder.typicode.com/posts'), headers: {'Content-Type': 'application/json'}, body: json.encode({'name': _name, 'email': _email}), ); if (response.statusCode == 201) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Form submitted successfully!')), ); } else { setState(() { _errorMessage = 'Failed to submit. Please try again.'; }); } } setState(() { _isSubmitting = false; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('User Form')), body: Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, child: Column( children: [ TextFormField( decoration: InputDecoration(labelText: 'Name'), onSaved: (value) => _name = value ?? '', validator: (value) { if (value == null || value.trim().isEmpty) { return 'Name is required'; } return null; }, ), TextFormField( decoration: InputDecoration(labelText: 'Email'), onSaved: (value) => _email = value ?? '', validator: (value) { if (value == null || value.trim().isEmpty) { return 'Email is required'; } if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) { return 'Enter a valid email'; } return null; }, ), SizedBox(height: 16), if (_errorMessage != null) Text(_errorMessage!, style: TextStyle(color: Colors.red)), SizedBox(height: 16), ElevatedButton( onPressed: _isSubmitting ? null : _submitForm, child: _isSubmitting ? CircularProgressIndicator() : Text('Submit'), ), ], ), ), ), ); } }
When you receive validation errors from an API, you should map them to the correct form fields so users know what to fix. In the code above, if the API returns an error, you display a message at the top of the form. For more precise feedback, you could parse the error response and show messages next to the specific fields that failed validation, helping users quickly correct their input.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
How can I validate form input in Flutter before sending it to the backend?
What is the best way to handle and display API validation errors in a Flutter form?
Can you show an example of mapping API errors to specific form fields in Flutter?
Awesome!
Completion rate improved to 6.67
Forms and POST Requests
Swipe to show menu
When you need to send user-generated data to a backend, you often use a form in your Flutter app. Forms let users enter information, such as their name or email, which you then collect and send to an API. To send this data, you typically use a POST request, which creates or updates data on the server. Before sending, it is important to validate the input to ensure that only correct and expected data is transmitted. This prevents unnecessary errors and improves your appβs reliability.
main.dart
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; void main() => runApp(FormPostDemo()); class FormPostDemo extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: UserFormPage(), ); } } class UserFormPage extends StatefulWidget { @override _UserFormPageState createState() => _UserFormPageState(); } class _UserFormPageState extends State<UserFormPage> { final _formKey = GlobalKey<FormState>(); String _name = ''; String _email = ''; String? _errorMessage; bool _isSubmitting = false; Future<void> _submitForm() async { setState(() { _errorMessage = null; _isSubmitting = true; }); if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); final response = await http.post( Uri.parse('https://jsonplaceholder.typicode.com/posts'), headers: {'Content-Type': 'application/json'}, body: json.encode({'name': _name, 'email': _email}), ); if (response.statusCode == 201) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Form submitted successfully!')), ); } else { setState(() { _errorMessage = 'Failed to submit. Please try again.'; }); } } setState(() { _isSubmitting = false; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('User Form')), body: Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, child: Column( children: [ TextFormField( decoration: InputDecoration(labelText: 'Name'), onSaved: (value) => _name = value ?? '', validator: (value) { if (value == null || value.trim().isEmpty) { return 'Name is required'; } return null; }, ), TextFormField( decoration: InputDecoration(labelText: 'Email'), onSaved: (value) => _email = value ?? '', validator: (value) { if (value == null || value.trim().isEmpty) { return 'Email is required'; } if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) { return 'Enter a valid email'; } return null; }, ), SizedBox(height: 16), if (_errorMessage != null) Text(_errorMessage!, style: TextStyle(color: Colors.red)), SizedBox(height: 16), ElevatedButton( onPressed: _isSubmitting ? null : _submitForm, child: _isSubmitting ? CircularProgressIndicator() : Text('Submit'), ), ], ), ), ), ); } }
When you receive validation errors from an API, you should map them to the correct form fields so users know what to fix. In the code above, if the API returns an error, you display a message at the top of the form. For more precise feedback, you could parse the error response and show messages next to the specific fields that failed validation, helping users quickly correct their input.
Thanks for your feedback!