Execute a function repeatedly in Flutter

Running a task once a while is a common task in most features.

Table of Contents

Timer

Timer is a count-down timer that can be configured to fire once or repeatedly.

import 'dart:async';

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

class TimerPage extends StatefulWidget {
  final String? title;

  TimerPage({Key? key, this.title}) : super(key: key);

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

class _TimerPageState extends State<TimerPage> {
  late Timer timer;
  String time = '';

  void __displayTime() {
    setState(() {
      time = '${Jiffy().yMMMMEEEEd}\n${Jiffy().hour}:${Jiffy().minute}:${Jiffy().second}';
    });
  }

  @override
  void initState() {
    super.initState();

    __displayTime();
    timer = Timer.periodic(Duration(seconds: 1), (_) => __displayTime());
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title!),
      ),
      body: Center(child: Text(time, style: TextStyle(color: Colors.blue, fontSize: 24.0))),


      floatingActionButton: FloatingActionButton(
        onPressed: __displayTime,
        tooltip: 'Show',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

cron

cron is not a real package to create cron job, but it is a cron-like time-based job scheduler for Dart. It can run tasks periodically at fixed times or intervals defined with a cron time string.

This package allows developer to handle specific running time better. For example, you can make a function to be executed at an exact period such as 12:00 at noon, every 6 past 15.

final cron = Cron();
cron.schedule(Schedule.parse('* * * * *'), () async {
	print('execute every minute');
});
cron.schedule(Schedule.parse('3-7 * * * *'), () async {
	print('between every 3 and 7 minutes');
});

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close