10.4 C
New York
Thursday, November 23, 2023

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

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 get our hands dirty by writing some code.

Using Future.delayed

A quick sample:

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(MyApp());
}

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

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

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

class _HomePageState extends State<HomePage> {
  void _showDialog() {
    Future.delayed(Duration(seconds: 2), () {
      showDialog(
          context: context,
          builder: (_) => SimpleDialog(
                title: Text('Have a nice day'),
                children: [Text('Happy coding with Flutter')],
                contentPadding: EdgeInsets.all(25),
              ));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _showDialog,
          child: Text('Show the Dialog'),
        ),
      ),
    );
  }
}

Using a Timer

AdvertisementsMinimal example:

@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”.

Advertisements

The code:

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

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

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

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

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

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

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

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

You can see the details about Timer in this article.

References

You can find more information about the tools used in the examples above in the Flutter official documentation:

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.

Advertisements

Related Articles

Latest Articles