DateTime handling with supercharged in Flutter

Felix Blaschke
2 min readFeb 29, 2020

--

With the 1.2.0 release of the Flutter package supercharged I introduced some handy DateTime and Duration features.

You can easily work with more natural Duration objects like 30.seconds or 250.milliseconds . You can also add them together: var duration = 1.minutes + 30.seconds; .

Especially when you are working with animations (for example when using simple_animations) these natural durations makes your code look great.

But they are also great for computing DateTime objects:
var future = 2.days.fromNow() + 5.minutes;

Supercharged allows you to call .fromNow()on any duration to create DateTime objects. Then you can add even more durations on it. It also works in the opposite direction: var past = 5.minutes.ago() .

Now let’s get into an example. Imaging you write a hotel booking app with some date cards. These cards represents bookable dates for a certain room:

Non-styled date selection cards

Supercharged introduces an .until() function for any DateTime object. It allows you to pass in a destination date as an argument, like this:
DateTime.now().until(6.days.fromNow())

It returns a lazy iterable of DateTime, each repesenting one day. (You can also specify the iteration interval by setting the optional by named parameter).

On this iterable we call supercharged’s .chunked() function. It splits up a list of values into a chunks of a certain size. In our example we want a chunk size of 3 .

The result is a nested list: [[A,B,C],[D,E,F],[G]] . By setting the fill argument on chunked() we can make him fill up the last chunk. In our example we fill it up with null values since we want to keep the 3x3 structure.

Then it looks like this: [[A,B,C],[D,E,F],[G,null,null]] . This is a perfect base for rendering. Here’s the Flutter code:

As you can see, the value restructuring part only takes just a few lines of code. The most of the code is rendering related.

You can use supercharged for your Flutter project today. It’s enterprice-ready and fully tested. It adds 60+ features to the dart language. Just have a look on all features:

If you enjoyed my work, I’d be happy to get some clapps or likes on my package page.

Until next time.
— Felix —

--

--

No responses yet