How to Catch Exception In Flutter

How to Catch Exception In Flutter?

If you want to find out the exact type of error you are getting, remove the exception so that all errors are caught, put a breakpoint within the catch, and check the type of error. so in this article, we will go through How to Catch Exception In Flutter

How to Catch Exception In Flutter?

Try with the below code snippet:

1. try-catch block:

  • This is the most basic approach for handling specific exceptions:
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(
      title: 'Try-Catch Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Network Request with Try-Catch'),
        ),
        body: Center(
          child: DataFetcher(),
        ),
      ),
    );
  }
}

class DataFetcher extends StatefulWidget {
  @override
  _DataFetcherState createState() => _DataFetcherState();
}

class _DataFetcherState extends State {
  String _data = 'Fetching data...';

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  Future _fetchData() async {
    const String url = 'https://jsonplaceholder.typicode.com/posts/1';
    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        setState(() {
          _data = data.toString();
        });
      } else {
        // If the server did not return a 200 OK response,
        // throw an exception.
        throw Exception('Failed to load data');
      }
    } catch (e) {
      setState(() {
        _data = "Error fetching data: $e";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(_data),
    );
  }
}

2. Asynchronous exception handling:

  • Use async and await keywords to catch exceptions within asynchronous operations:
import 'dart:io'; // Import dart:io for handling SocketException
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(
      title: 'Try-Catch Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Network Request with Try-Catch'),
        ),
        body: Center(
          child: DataFetcher(),
        ),
      ),
    );
  }
}

class DataFetcher extends StatefulWidget {
  @override
  _DataFetcherState createState() => _DataFetcherState();
}

class _DataFetcherState extends State {
  String _data = 'Fetching data...';

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  Future _fetchData() async {
    const String url = 'https://jsonplaceholder.typicode.com/posts/1';
    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        setState(() {
          _data = data.toString();
        });
      } else {
        // If the server did not return a 200 OK response,
        // throw an exception.
        throw HttpException(
            'Failed to load data with status code: ${response.statusCode}');
      }
    } on SocketException catch (e) {
      setState(() {
        _data = "Network error: Please check your internet connection: $e";
      });
    } on HttpException catch (e) {
      setState(() {
        _data = "Server error: $e";
      });
    } catch (e) {
      setState(() {
        _data = "Error fetching data: $e";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(_data),
    );
  }
}

3. catchError on Future objects:

  • Chain a catchError method to a Future to handle errors:
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(
      title: 'CatchError Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Network Request with catchError'),
        ),
        body: Center(
          child: DataFetcher(),
        ),
      ),
    );
  }
}

class DataFetcher extends StatefulWidget {
  @override
  _DataFetcherState createState() => _DataFetcherState();
}

class _DataFetcherState extends State {
  String _data = 'Fetching data...';

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  Future _fetchData() async {
    const String url = 'https://jsonplaceholder.typicode.com/posts/1';
    http.get(Uri.parse(url)).then((response) {
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        setState(() {
          _data = data.toString();
        });
      } else {
        throw Exception('Failed to load data');
      }
    }).catchError((error) {
      setState(() {
        _data = "Error fetching data: $error";
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(_data),
    );
  }
}

Conclusion:

Thanks for being with us on a Flutter Journey !!!

So in this article, We have been through How to Catch Exception In Flutter.

Keep Learning !!! Keep Fluttering !!!

Let us know in the comments if you are still facing any problems in Flutter development!! We are here to help you 🙂

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields