dart : compute data in the model

Dart custom getters (and how to compute data in your models)

I’m currently working on a POC for a tablet app, where the UI will display a lot of computed data directly from the models. For doing such a thing, I had to use Dart custom getters. As you might know, using getters and setters in Dart for security reasons only is an anti-pattern, this is not a good practice (because Dart already provides it by default). But you can override default getters and setters if you need to add some logic to them.

First of all, I was a little annoyed because I was trying to compute my data in a setter, but actually, I didn’t need to “set” anything. I just wanted my model to compute this specific value from its already known values, and provide it to me when I call my “object.specificValue”.

As I couldn’t find any example for doing this, I thought maybe this was not the right way to do that. But this way of coding things has been validated by my lead dev, so, I think this could help someone who tries to compute data directly from a model’s getter.

So let’s say I have a sensor, that have an alert status (this piece of code is just for example, this is only a snippet, not a complete model). Let’s say this sensor watches the the moisture content of a plant’s soil, and has to throw an alert if the level is too low.

This sensor needs a status, which is another model and provides the sensor levels :

Now, let’s say I want to compute the alert status of my sensor, depending on the currentLevel and the alertLevel, I could do this in my widget build method (in the UI), I could do this in a helper abstract class… But this kind of logic has nothing to do with the UI right? So these options will work fine, but are definitely not good solutions for keeping your code clean and easy to maintain.

Otherwise, I can do it in a custom getter, directly in my model, so that the business logic stays in the logic layer, and the UI only calls the “status.alert” getter to know if the moisture level detected by my sensor is too low.

Let’s code this :

I put this piece of logic in a getter (and not a setter) because I do not need to set any value, I need it to be computed directly when I’m calling it. If I wanted to compute this value while passing a parameter, I should have used a setter instead.

Sure, you can take the logic way further, but I tried to keep this example simple to show how to do it.

Hope this will help some of you folks !


Hi ! I'm a junior IoT developer and UX designer. Living in France, mother of 2, bookworm, cats lover, Flutter girl, yada yada yada. The usual stuff. Let's talk about code !

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

back to top