Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Error Handling Patterns | REST Fundamentals in Flutter
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Flutter REST API Integration

bookError Handling Patterns

When building Flutter apps that communicate with REST APIs, you will encounter several types of errors. The most common are HTTP errors, such as 404 (not found) or 500 (server error), which occur when the server responds with an error status code. Network errors happen when there is no internet connection or the server is unreachable. Parsing errors occur if the app fails to decode the response data, often due to unexpected or malformed JSON.

main.dart

main.dart

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: ErrorHandlingDemo(), ); } } class ErrorHandlingDemo extends StatefulWidget { @override _ErrorHandlingDemoState createState() => _ErrorHandlingDemoState(); } class _ErrorHandlingDemoState extends State<ErrorHandlingDemo> { String _result = ''; Future<void> fetchData() async { setState(() { _result = 'Loading...'; }); try { final response = await http.get(Uri.parse('https://invalid-url.com/data')); if (response.statusCode == 200) { final data = json.decode(response.body); setState(() { _result = 'Success: $data'; }); } else { setState(() { _result = 'Error: Unable to fetch data (Status ${response.statusCode})'; }); } } catch (e) { setState(() { _result = 'Something went wrong. Please check your connection and try again.'; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Error Handling Example')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_result), SizedBox(height: 20), ElevatedButton( onPressed: fetchData, child: Text('Fetch Data'), ), ], ), ), ); } }

The try-catch block in the code above helps your app respond gracefully to errors. Instead of crashing or showing confusing error codes, the app displays a clear message if something goes wrong. This approach gives users feedback and keeps the app running smoothly, even when the network is unreliable or the server returns unexpected data.

Note
Note

Showing user-friendly error messages improves trust and satisfaction. Avoid exposing raw error codes or technical details, as these can confuse or worry users.

question mark

What is the main benefit of using try-catch when making API calls in Flutter?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 4

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

bookError Handling Patterns

Svep för att visa menyn

When building Flutter apps that communicate with REST APIs, you will encounter several types of errors. The most common are HTTP errors, such as 404 (not found) or 500 (server error), which occur when the server responds with an error status code. Network errors happen when there is no internet connection or the server is unreachable. Parsing errors occur if the app fails to decode the response data, often due to unexpected or malformed JSON.

main.dart

main.dart

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: ErrorHandlingDemo(), ); } } class ErrorHandlingDemo extends StatefulWidget { @override _ErrorHandlingDemoState createState() => _ErrorHandlingDemoState(); } class _ErrorHandlingDemoState extends State<ErrorHandlingDemo> { String _result = ''; Future<void> fetchData() async { setState(() { _result = 'Loading...'; }); try { final response = await http.get(Uri.parse('https://invalid-url.com/data')); if (response.statusCode == 200) { final data = json.decode(response.body); setState(() { _result = 'Success: $data'; }); } else { setState(() { _result = 'Error: Unable to fetch data (Status ${response.statusCode})'; }); } } catch (e) { setState(() { _result = 'Something went wrong. Please check your connection and try again.'; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Error Handling Example')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_result), SizedBox(height: 20), ElevatedButton( onPressed: fetchData, child: Text('Fetch Data'), ), ], ), ), ); } }

The try-catch block in the code above helps your app respond gracefully to errors. Instead of crashing or showing confusing error codes, the app displays a clear message if something goes wrong. This approach gives users feedback and keeps the app running smoothly, even when the network is unreliable or the server returns unexpected data.

Note
Note

Showing user-friendly error messages improves trust and satisfaction. Avoid exposing raw error codes or technical details, as these can confuse or worry users.

question mark

What is the main benefit of using try-catch when making API calls in Flutter?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 4
some-alt