flutter dart then vs whenComplete vs catchError
flutter dart then vs whenComplete vs catchError

Hi Guy’s, Welcome to Proto Coders Point, In this Flutter Article let’s then whenComplete and catchError in Flutter Dart.

In Flutter/Dart Programming language, We make use of then, whenComplete, and catchError methods are used with Futures to handle asynchronous task operation in flutter dart.

1. then : Used to handle the success completion of a Future and then access the result.
.then() only works if the Future task like fetching data from server is success (without any errors).

2. whenComplete : Used to execute a callback function whenever the Future completes, regardless of success or error. Means even if there is any error whenComplete will get executed. It’s similar to finally this is like default result.

3. catchError: Used to handles error caught while fetching Future result or Future logic has some error in it.

Code Example to demonstrate then,whenComplete and catchError with Future in Dart:

import 'dart:async';

void main() {

  // Example Future that resolves after 2 seconds
  Future<String> fetchData() {
    return Future.delayed(Duration(seconds: 2), () => "Data fetched successfully");
  }

  // Example Future that throws an error after 3 seconds
  Future<String> simulateError() {
    return Future.delayed(Duration(seconds: 3), () => throw Exception("Error occurred"));
  }

  // Using then to handle successful completion
  fetchData().then((data) {
    print("Data: $data");
  }).catchError((error) {
    print("Error fetching data: $error");
  });

  // Using whenComplete to execute code regardless of success or failure
  simulateError().then((data) {
    print("Data: $data");
  }).catchError((error) {
    print("Error fetching data: $error");
  }).whenComplete(() {
    print("Completed");
  });
}

OutPut

Data: Data fetched successfully
Error fetching data: Exception: Error occurred
Completed