How to Run Code After Time Delay in Flutter App

While building an app, you may need to execute code after some time delay. In this example, we are going to show you the way to run dart code after some second, minute, hour delay. See the example below for more details after the Future task.

Future.delayed(Duration(seconds: 5), (){
      print("Executed after 5 seconds");
});

Future.delayed(Duration(minutes: 2), (){
    print("Executed after 2 minutes");
});

Future.delayed(Duration(minutes: 1, seconds: 4), (){
      print("Executed after 1 minute 4 seconds");
});

You can add more attributes in Duration() class, such as hours, day, milliseconds, microseconds. 

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: Scaffold(
        appBar: AppBar(title:Text("Execute Code After Delay")),
        body: Container(
          padding: EdgeInsets.all(20),
          alignment: Alignment.center, 
          child: Column(
             children: [
                 ElevatedButton( 
                    child: Text("Execute Code After 5 Seconds"),
                    onPressed: (){
                      Future.delayed(Duration(seconds: 5), (){
                         print("Executed after 5 seconds");
                      });
                    },
                 ),

                 ElevatedButton( 
                    child: Text("Execute Code After 2 Minutes"),
                    onPressed: (){
                      Future.delayed(Duration(minutes: 2), (){
                         print("Executed after 2 minutes");
                      });
                    },
                 ),

                 ElevatedButton( 
                    child: Text("Execute Code After 1 Minute 4 seconds"),
                    onPressed: (){
                      Future.delayed(Duration(minutes: 1, seconds: 4), (){
                         print("Executed after 1 minute 4 seconds");
                      });
                    },
                 )
             ],
          ),
        )
      )
    );
  }
}

In this way, you can execute code after a time delay in Flutter App.

No any Comments on this Article


Please Wait...