Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Forms and POST Requests | Real Data in UI
Flutter REST API Integration

bookForms 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

main.dart

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
import '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.

question mark

What is the main reason to validate form input before sending a POST request?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 3

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

bookForms and POST Requests

Svep för att visa menyn

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

main.dart

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
import '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.

question mark

What is the main reason to validate form input before sending a POST request?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 3
some-alt