Kinda Code
Home/Flutter/Flutter: 2 Ways to Run a Piece of Code after a Delay

Flutter: 2 Ways to Run a Piece of Code after a Delay

Last updated: August 06, 2023

This article demonstrates 2 different ways to execute a piece of code after a delay in Flutter. The first approach is to use Future.delayed, and the second one is to use a timer. Without any further ado, let’s get our hands dirty by writing some code.

Note: This article was recently updated to work properly with Flutter 3 and later

Using Future.delayed

TL;DR

Here’s the point:

Future.delayed(Duration(milliseconds: 1500), () {
    print('Hello');
});

Complete Example

This demo app shows a greeting dialog after 2 seconds after the button is pressed.

Preview:

The full source code:

// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Kindacode.com',
        theme: ThemeData(
          primarySwatch: Colors.amber,
        ),
        home: const HomePage());
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // this function is called when the button gets pressed
  void _showDialog() {
    // delay 2 seconds
    Future.delayed(const Duration(seconds: 2), () {
      // show the dialog
      showDialog(
          context: context,
          builder: (_) => const SimpleDialog(
                title: Text('Have a nice day'),
                contentPadding: EdgeInsets.all(25),
                children: [Text('Happy coding with Flutter')],
              ));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      ),
      body: Center(
        // this button is used to trigger the _showDialog function
        child: ElevatedButton(
          onPressed: _showDialog,
          child: const Text('Show the Dialog'),
        ),
      ),
    );
  }
}

Using a Timer

TL;DR

Minimal implementation:

@override
void initState() {
    super.initState();
    Timer(Duration(seconds: 5), () {
      print('Hello');
    });
}

Complete Example

Preview

In the beginning, the text widget displays “Please wait…”. After 5 seconds, you will see “Everything is ready”.

The code:

// main.dart
import 'package:flutter/material.dart';
import 'dart:async';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Kindacode.com',
        theme: ThemeData(
          primarySwatch: Colors.amber,
        ),
        home: const HomePage());
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _text = 'Please wait...';

  @override
  void initState() {
    super.initState();
    Timer(const Duration(seconds: 5), () {
      setState(() {
        _text = 'Everything is ready';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      ),
      body: Center(
        child: Text(
          _text,
          style: const TextStyle(fontSize: 30),
        ),
      ),
    );
  }
}

You can see the details about Timer in this article.

Conclusion

We’ve covered 2 techniques to delay executing code in Flutter. If you’d like to explore more new and interesting features of Flutter and Dart, take a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.