How to run code after some delay in Flutter?

Cover Image for How to run code after some delay in Flutter?
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

Running code after a delay in Flutter made easy! 😎

So, you want to execute a function after a certain delay in your Flutter app? No worries, we've got you covered! 🚀

The Problem

Let's understand the problem first. You have a widget and you want to perform some action, like changing the style property, after a certain duration.

The Solution

Flutter provides a simple and idiomatic way to achieve this using the Future class and Future.delayed method. Here's how you can do it:

import 'package:flutter/material.dart';

class MyDelayedWidget extends StatefulWidget {
  @override
  _MyDelayedWidgetState createState() => _MyDelayedWidgetState();
}

class _MyDelayedWidgetState extends State<MyDelayedWidget> {
  @override
  void initState() {
    super.initState();
    _startDelayedTask();
  }

  Future<void> _startDelayedTask() async {
    await Future.delayed(Duration(seconds: 2)); // Change the duration as per your requirement
    setState(() {
      // Perform your action here, like changing the style property
    });
  }

  @override
  Widget build(BuildContext context) {
    return FlutterLogo();
  }
}

In the above example, we create a stateful widget MyDelayedWidget that extends StatefulWidget. In the state class _MyDelayedWidgetState, we override the initState method, which gets called when the widget is first created.

Inside the initState method, we call a private method _startDelayedTask. This method is marked async to allow us to use the await keyword. We use Future.delayed to introduce the desired delay of 2 seconds (you can change it as per your requirement). Once the delay is over, we call setState to update the widget and perform the desired action, like changing the style property.

In the build method, we simply return a FlutterLogo widget, which will be updated after the given delay.

Let's see it in action! 🎬

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Delayed Flutter'),
        ),
        body: Center(
          child: MyDelayedWidget(),
        ),
      ),
    );
  }
}

In the build method of your main app widget, you can simply add an instance of MyDelayedWidget inside a Center widget. The MyDelayedWidget will do its magic and update the style property after the specified delay.

A little more customization 🎨

What if you want to execute different actions after different delays? For example, changing the style property after 2 seconds, and changing another property after 5 seconds?

You can achieve this by creating multiple methods _startDelayedTask and calling them at appropriate places, as per your requirement.

Conclusion

Now you have the power to run code after a delay in your Flutter app. It's as easy as using Future.delayed and setState. Go ahead, give it a try, and level up your app's user experience! 🚀

If you have any questions or suggestions, feel free to leave a comment below. Happy coding! 💻

Keep Fluttering! 🦋


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello