Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do time based events in Flutter/Dart?

I am writing a Flutter app that turns a light on and off based on a time of day. So let's say the time range is to turn on at 5pm and off at 6pm. If the app is opened during this time or if the app is already opened when the time hits, the light would turn on.

I already have the light widget all worked out and will be using opacity to simulate the light on and off.

Container(
  height: MediaQuery.of(context).size.height * 0.18,
  decoration: new BoxDecoration(
    color: Colors.red.withOpacity(0.1),
    shape: BoxShape.circle,
  ),
),

I have been doing some research on Dart's DateTime, but I am not really sure where to start because I want the light to turn on if the app is opened during the "on" window. But also, if the app is already open before the "on" window it will poll in the background and if the "on" window hits, the light will turn on.

like image 679
ATLChris Avatar asked Jun 29 '19 23:06

ATLChris


1 Answers

Dart does have a few primitives that can be used to trigger events based on time as mentioned in this post: Does Dart have a scheduler?

When the app is open, using Stream.periodic() or possibly a package like cron for dart could help you achieve the desired outcome.

The tricky part is related to background execution. Android is much more liberal when it comes to executing background tasks, whereas iOS really locks down what you're able to do.

For Android, the Flutter team actually wrote a package called Android Alarm Manager, which takes advantage of the Android Alarm Manager service to execute Dart code when an alarm fires.

As far as I know, there isn't an exact equivalent for iOS. There's actually an entire thread about this on the Flutter Github. However, there is a package called background_fetch that allows you to take advantage of background execution on both platforms. During this time you could check a local database to see if a light has been scheduled to be turned on during that time and make the necessary call. Unfortunately, this isn't a precise mechanism so lights may not be turned on at the exact time that you'd like.

If it's an option, it would be much better to schedule these tasks server-side so that you have more fine-grained control over scheduling via cron or something similar.

like image 188
jdixon04 Avatar answered Oct 25 '22 12:10

jdixon04