Your First Flutter App: Polishing the App

Apr 12 2022 · Dart 2.14.1, Flutter 2.5, Visual Studio Code

Part 1: Introduction to Dart

07. Use Number Methods

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 06. Challenge: Rewrite Your Code Next episode: 08. Utilize Type Inference

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 07. Use Number Methods

abs method

Transcript: 07. Use Number Methods

At this point, you’ve simplified your algorithm to calculate the difference down to a few lines of code. That’s good, but we can do even better.

It turns out that in Dart, numbers like integers are objects. This differs from other languages like Java, where number types are known as what is called “primitive types”.

Since numbers are objects, it means we can call methods on them.

One handy method included in the dart core libraries is a method to get the absolute value of a number. Both of these expression shown here evaluate to positive 42.

In this exercise, we’ll finalize our revisions to the difference algorithm. Let’s dive in!

Okay, to get started, open your project in progress or download the starter project for this episode. Open up main.dart and scroll down to the _pointsForCurrentRound method.

We’re going to use a method called abs meaning absolute value. The absolute value is the distance from zero on the number line so the number is always positive.

Update the method to the following:

int _pointsForCurrentRound() {
    const int maximumScore = 100;
    int difference = _model.target - _model.current;
    return maximumScore - difference;
}

Now we want to get the absolute value of the target minus the current. To do this, we wrap the expression in parenthesis.

int difference = (_model.target - _model.current);

Now we call the abs method on the parenthesis itself.

int difference = (_model.target - _model.current).abs();

When this line is evaluated, the current value is subtracted from the target value. After which, the abs method is called on the resulting number.

And that’s it - we’ve simplified our code down to one line and made it easier to read in the process. That’s a net win. Nice work!