In Flutter, you can execute code after a delay using the Future.delayed
method or the Timer
class. Here are examples of both approaches:
Using Future.delayed
:
Future.delayed(Duration(seconds: 2), () { // Code to execute after a 2-second delay print("Code executed after a 2-second delay"); });
In this example, the code inside the function will be executed after a 2-second delay. You can adjust the duration according to your needs.
Using Timer
class:
import 'dart:async'; // ... Timer(Duration(seconds: 3), () { // Code to execute after a 3-second delay print("Code executed after a 3-second delay"); });
In this example, we use the Timer
class to schedule the code to run after a 3-second delay. The first argument to the Timer
constructor is the duration, and the second argument is the function to execute.
Both of these approaches allow you to introduce delays before executing code in your Flutter app. Choose the one that best fits your use case and coding style.