Open In App

Flutter – Future.delayed with Example

Last Updated : 14 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

You can use the Future.delayed method in Flutter to delay the execution of a piece of code for a specified duration. A sample video is given below to get an idea about what we are going to do in this article.

How to Use?

Dart




Future.delayed(Duration(seconds: 2), () {
  // code to be executed after 2 seconds
});


Duration(seconds: 2) specifies the duration to delay the execution by 2 seconds. The second argument to the Future.delayed method is a callback function that contains the code to be executed after the delay.

Step By Step Implementation

Step 1: Create a New Project in Android Studio or in vs code.

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Add the material package that gives us the important methods and then call the runApp method in the main function that will call our application.

import 'package:flutter/material.dart';

void main() {
   runApp(RunMyApp());
}

Step 3: Now we have to make a stateless widget RunMyApp Because our application does not go to change its state and then return the MaterialApp widget which allows us the set the title and theme and many more. Further in the home property give Delayedwidget (Not defined yet).

class RunMyApp extends StatelessWidget {

    const RunMyApp({super.key});
    
    @override
    Widget build(BuildContext context) {
     return MaterialApp(
          title: 'Delayed Example',
          debugShowCheckedModeBanner: false,
          theme: ThemeData(primarySwatch: Colors.green),
          home: DelayedWidget);
    }
}

Step 4: Let’s create A DelayedWidget class and this going to be a stateful widget

In this class, we defined the bool variable _showText which is used whether the text is shown or not.  Also, we create the Button in the center of the body, so that we can setState method. Inside the setState method, we use Future delay to delay for some time. Then we can simply display the text.

class DelayedWidget extends StatefulWidget {
  const DelayedWidget({super.key});

  @override
  _DelayedWidgetState createState() => _DelayedWidgetState();
}

class _DelayedWidgetState extends State<DelayedWidget> {
  bool _showText = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Delayed Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (_showText)
              Text(
                'Delayed Text GeeksforGeeks',
                style: TextStyle(fontSize: 24),
              ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _showText = false;
                });

                Future.delayed(Duration(seconds: 3), () {
                  setState(() {
                    _showText = true;
                  });
                });
              },
              child: Text('Show Text After Delay 3 seconds'),
            ),
          ],
        ),
      ),
    );
  }
}

We use the setState method to change the state of the _showText variable, We first make it false and then Use the Future delay of the 3 seconds. Further makes _showText to true. 

Code Example

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(RunMyApp());
}
  
class RunMyApp extends StatelessWidget {
  const RunMyApp({super.key});
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Delayed Example',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.green),
      home: DelayedWidget(),
    );
  }
}
  
class DelayedWidget extends StatefulWidget {
  const DelayedWidget({super.key});
  
  @override
  _DelayedWidgetState createState() => _DelayedWidgetState();
}
  
class _DelayedWidgetState extends State<DelayedWidget> {
  bool _showText = false;
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Delayed Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (_showText)
              Text(
                'Delayed Text GeeksforGeeks',
                style: TextStyle(fontSize: 24),
              ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _showText = false;
                });
  
                Future.delayed(Duration(seconds: 3), () {
                  setState(() {
                    _showText = true;
                  });
                });
              },
              child: Text('Show Text After Delay 3 seconds'),
            ),
          ],
        ),
      ),
    );
  }
}


Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads