Execute a Function Repeatedly in Flutter

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

Table of Contents

Timer

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

import 'dart:async';

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  Timer _timer;

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

  void startTimer() {
    const oneSec = const Duration(seconds: 1); // define the duration for how often you want to call the function
    _timer = new Timer.periodic(
      oneSec,
      (Timer timer) => setState(
        () {
          // place the function you want to execute here
          print('Function executed');
        },
      ),
    );
  }

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

  @override
  Widget build(BuildContext context) {
    return Container();  // replace with your widget
  }
}
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 a 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 developers to handle specific running times 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 *


Scroll to Top