Execute a Function with Delay Time in Flutter Dart Example

Timer class in flutter is used to create a count down timer that can be executed on a particular time. The timer class object can be fire once or repeatedly as per user requirement. We can also configure time in seconds and milliseconds in Timer. Timer class is the part of dart:async package. So in this tutorial we would use the Timer class object to execute a function with delay time in flutter android iOS app.

Contents in this project Execute a Function with Delay Time in Flutter Dart Example:

1. Open your project’s main.dart file and import material.dart package and dart:async package.

2. Creating void main runApp() method and here we would call our main MyApp class.

3. Creating our main Root parent class named as MyApp extends StatelessWidget. In this class we would call our AppState() class as Child widget.

4. Creating AppState class extends StatefulWidget. In this class we would make the createState() method and pass our State class in which we would be using States.

5. Creating our main Child State class named as AppUpdate extends State<AppState>.

6. Creating a object of Timer class named as _timer. Timer class is used to fire a Task or set of code after a particular time in flutter. You can read more about Timer class on here on Flutter’s official page.

7.  Creating a String variable named as sampleText with some random text.

8. Creating a function named as updateText(). Inside the function we would call the _timer method and here we would update the sampleText String variable after 4 seconds of delay using setState() method.

9. Creating the dispose() method and dispose the object when it removed from tree.

10. Creating Widget Build area -> Scaffold widget -> Center widget -> Column widget -> Text widget and RaisedButton widget.

11. Complete source code for main.dart file:

Screenshot:

Execute a Function with Delay Time in Flutter Dart Example

Leave a Reply

Your email address will not be published. Required fields are marked *