Everything You Need to Know About Future Delayed Flutter

Hermione at Pangea.ai
Godwin Oluponmile
Published: 17.10.2022

If you’re planning to build a Flutter application that delivers a mind-blowing user experience, setting up Future Delayed in your loading states becomes a vital box to tick before deploying your application to users.

Imagine a scenario where you're building a cross-platform application, such as an iOs, android, web, or desktop application, and you need to create a loading state. The state may require that you load pictures from a web server or texts to display in multiple languages from the device memory. You can even be in a situation where you'll need to loaf a user's data from an external or local database. While doing these, you may notice some delays. In this case, the use of the Future Delayed Flutter method comes to the rescue.

The future.delayed on a white background with a blue border

However, there are other various methods to delay code execution in Flutter, such as scheduleMicrotask, Future.microtask, Future, Timer.run, WidgetsBinding.addPostFrameCallback, and SchedulerBinding.addPostFrameCallback; but today, we are discussing the Future Delayed method.

You will also learn about Futures with a step-by-step guide on implementing the Future Delayed function in your Flutter applications.

What is a Future in Flutter?

A Future is one of the essential concepts in software engineering that you can use in Flutter. It is an object which represents a Delayed computation. It represents a value or an error that will be accessible later on.

Unlike a synchronous function that returns a result immediately, a Future is an asynchronous function that doesn’t get completed instantly. Instead, it returns a state, which will eventually contain the result.

There are three states a Future can return:

  1. Uncompleted: This means that the output of the Future is still closed and awaiting a response.
  2. Completed with Data: This means that the output of the Future is open, and the data is ready.
  3. Completed with Error: This means that the output of the Future is open, but something went wrong.
  4. In this case, it is crucial to consider that you may need to catch the error that the function throws and determine how to handle detected errors or exceptions.

    How to use a Future

    There are two significant ways to execute a Future and use the value it returns:

    1. Await on the Future to return: This is the most common way to execute a Future, and for this to work, the function calling the code has to be marked async. You also need to ensure that both the caller function and any functions called within that function use the async modifier.
    2. Here is a coding example demonstrating how this works:

      Future getProductionCostForUser() async {

      var user = await getUser();

      var order = await getOrder(user.uid);

      var production = await getProduction(order.productionId);

      return production.totalCost;

      }

      main() async {

      var cost = await getProductionCostForUser();

      print(cost);

      }

      1. Using .then function: This is another way to handle a Future if you don’t want to mark it async. A .then takes in a function that will be called with the value type of your Future. It is similar to a Promise in JavaScript but doesn’t have the resolve or reject explicitness.
      2. void main() {

        Future.Delayed(

        const Duration(seconds: 3),

        () => 100,

        ).then((value) {

        print('The value is $value.'); // Prints later, after 3 seconds.

        });

        print('Waiting for a value...'); // Prints first.

        }

        How to handle errors returned in a Future state

        • Using then’s onError: This allows you to pass a callback that will be called when the Future completes.
        • Using catchError: This is used to handle errors emitted by the Future.

        • Using onError: onError can be used to handle errors thrown by the Future.
        • Using whenComplete: You use this when a code has to be executed regardless of whether the Future completes with an error or not.
        • Using Try-Catch-Block: The catch block in try-catch-block can accept either one or two parameters, so if an error is thrown, the error gets passed as the first argument, which is often almost required, while a complete log of the error will also get passed as the second argument, which is called a StackTrace.
        • Using Try-Catch-Finally: This is not known to most Flutter developers, but it is a type of Try-Catch-Block with an addition of the Finally function.

        It forcefully breaks out of the code execution after an error has been thrown, or a response has been gotten.

        How to set Future delays in your Flutter applications

        You are probably wondering how to set the Future Delayed Flutter function in Flutter projects. At Pangea, we don’t just give you theoretical illustrations of Flutter concepts; we also detail how to apply these concepts to your projects.

        Below is a step-by-step guide on how to set a Future delay in your Flutter application:

        Step 1: Begin by adding the Future.Delayed() widget

        Step 2: Set the duration. When using a Future Delayed in Flutter, you have to set a duration, which translates to the waiting time. Setting duration is essential because a user may not know how long a Future will run while observing the screen loading indicator. You need to set a period to avoid a situation where the screen continues to load non-stop.

        After adding the Future.Delayed() widget, input the Duration (the duration can be 3 seconds, 5 minutes, or whatever works for the function you want to execute) inside the widget.

        Step 3: Write the callback function: The callback function is a method we pass in an argument to perform the required action.

        Here is a coding example of how the function is used:

        Future.Delayed(Duration(seconds: 2), () { // <-- Delay here

        setState(() {

        _isLoading = false; // <-- Code run after delay

        });

        });

Execute code after delay functions in blue boxes on a white background

Future Delay Use Case Instances in Flutter and Code Examples

  1. Here is a coding example of how to use Future delay to create a splash screen-
  2. Future.Delayed(Duration(seconds: splashtime), () async {

    Navigator.pushReplacement(context, MaterialPageRoute(

    //pushReplacement = replacing the route so that

    //splash screen won't show on back button press

    //navigation to Home page.

    builder: (context){

    return Home();

    }));

    });

    1. Here is a coding example of how to use Future delay to navigate to a new page-
    2. Future.Delayed(Duration(seconds: 5), () {

      // 5s over, navigate to a new page

      Navigator.pushNamed(context, MaterialPageRoute(builder: (_) => Screen2()));

      });

      Conclusion

      When building a Flutter application, users may need to navigate between pages or load a button. You don’t want them stuck on a frozen page wondering what's happening. Implementing a Future Delayed Flutter is vital for a great User Experience.

      You can efficiently perform background tasks like API calls or database queries on the backend without disrupting the flow of the app on the user’s screen when you set the Future Delayed appropriately.

      You can also check out our official Flutter documentation for detailed information on how the Future Delayed method was developed.

      FAQs:

      Q1. How do you stop Future delay in Flutter?

      You can stop a Future delay in Flutter using async package, by using timeout method, or through converting the future to a stream. Here's a further breakdown:

      • Using async package: The async package provides a utility synonymous with the dart:async class, which is used to enhance asynchronous computations. To cancel a Future, you need to use the CancelableOperation class.

      Here is a code example:

      var cancelMyFuture = CancelableOperation.fromFuture(

      Future inner,

      { FutureOr onCancel()? }

      )

      // call the cancel() method to cancel the Future

      myCancelableFuture.cancel();

      • Using timeout() method:

      The timeout method is quick and simple, although it is not very flexible. You can use the timeout method to limit time for a Future; if the Future is completed in time, it will return its value. However, if the Future isn't completed in time, it will execute an onTimeout function.

      Here is a code example :

      Future timeout(

      Duration timeLimit,

      {FutureOr onTimeout()?}

      )

      • Converting the Future to a stream:

      This works by using the asStream method of the Future class to create a stream containing the result of the original Future.

      Then you can proceed to cancel a subscription to the stream.

      Below is a code example

      import 'dart:async';

      // Create a demo Future

      Future _loadData() async {

      await Future.Delayed(const Duration(seconds: 10));

      return 'Some Data';

      }

      // a reference to the stream subscription

      // so that we can call _sub.cancel() later

      StreamSubscription? _sub;

      // convert the Future to a stream

      _sub = _loadData().asStream().listen((data) {

      // do something with "data"

      print(data);

      });

      // cancel the stream subscription

      _sub.cancel();

      Q2. Why is Future used in Flutter?

      Future is used in Flutter to show a potential value or error that will become available later after completion. You can complete a Future in two ways:


      • With a value (“this signifies that the Future succeeded”)
      • With an error (“this signifies that the Future failed)

      Q3. How do you delay a text on Flutter?

      There are various ways to delay a text in your Flutter application and they include:

      • Future.Delayed
      • scheduleMicrotask
      • Future.microtask
      • Future
      • Timer.run
      • WidgetsBinding.addPostFrameCallback
      • SchedulerBinding.addPostFrameCallback

Need help selecting the right company?

We will do the work for you, all for free.


Tell us what you need