How to use Dart Math in Flutter

Dart Math library is full of many in-built Mathematical functions. We can implement these properties, and methods in our Flutter App.

Let us build a “Mood Swing App” to understand the magic of Dart Math library.

In our previous sections we have learned a lot of new features in Flutter. That includes how to refactor code, anonymous functions, and moreover, the role of Stateful widget. We have also built a simple Photo App that changes when we tap any image.

However, the Photo App was too simple. We have tried to give an idea. Therefore, we used a List index to change the State of the images.

The problem was we cannot change each image separately. Whenever we click any image that changes all the images placed in the Row Widget.

The Dart Math library can solve this problem.

Let us see how.

In our “Mood Swing App” we have a few pictures of faces that represent different types of Moods.

Now, in the Row Widget, we place two faces side by side.

Our challenge is to click any face, and change two faces simultaneously.

While building this “Mood Swing App” we have used the Stateful Widget and the setState() method.

Let us go through the code first. Then we will discuss the code.

import 'dart:math';
import 'package:flutter/material.dart';

class AppHomePage extends StatefulWidget {
  const AppHomePage({Key? key}) : super(key: key);

  @override
  State<AppHomePage> createState() => _AppHomePageState();
}

class _AppHomePageState extends State<AppHomePage> {
  int leftFaceIndex = 1;
  int rightFaceIndex = 1;
  void changeMood() {
    setState(() {
      leftFaceIndex = Random().nextInt(4);
      rightFaceIndex = Random().nextInt(4);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white70,
      appBar: AppBar(
        title: const Text('Mood Swing App'),
      ),
      body: Center(
        child: Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    changeMood();
                  },
                  child: Image.asset('images/face${leftFaceIndex + 1}.jpg'),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    changeMood();
                  },
                  child: Image.asset('images/face${rightFaceIndex + 1}.jpg'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

If we run the “Mood Swing App”, any type of face may appear on the screen.

However, click any image. That will change both faces on the screen.

Dart Math library in Flutter App
Dart Math library in Flutter App generates any face

Certainly, two faces represent two types of Moods. Now we can click any image and that changes both faces.

However, since the face is generated by random numbers, it it not certain which face will appear when and where.

Mood Swing App in Flutter changes moods reflected on faces
Mood Swing App in Flutter changes moods reflected on faces
If you are interested to run the full code, please clone from the respective GitHub Repository.

What is dart Math?

Before discussing the above code, we need to understand how the Dart Math library works.

We can use the DartPad console to test the code.

import'dart:math';
void main() {
  
  int randomNumber = Random().nextInt(11);
  
  print(randomNumber);  
  
}

Firstly, we have imported the Dart Math library.

Secondly, we have called the nextInt() method using the Random() class.

What is the speciality of the nextInt() method?

It takes one argument, or parameter that refers to any number. In our code, we have used 11. Now, the nextInt(11) will generate any number between 0 to 10. In other words, the random number generator includes 0 but excludes 11 which we have passed as parameter.

As a result, if we run the code, each time it generates any number between 0 to 10.

It might be 2, 5, 0, 7, or any number between 0 to 10.

Now, the question is how we can leverage its advantage in our Flutter App.

Remember this key point.

dart:math library is an inbuilt library in dart. It contains different mathematical constants, and mathematical functions.

There are also a few classes as we have used in the above code.

How do you import Dart Math into Flutter?

We have imported the Dart Math library on the top of the file first.

import 'dart:math';

After that, we keep our images in our images folder. We have used the names of the images as follows.

The first image starts with the name “face1” and lasts upto “face4.” Dart allows us to use String interpolation.

As a result, we can interpolate these numbers inside the Image.asset() constructor path which is a String.

child: Image.asset('images/face${leftFaceIndex + 1}.jpg'),
child: Image.asset('images/face${rightFaceIndex + 1}.jpg'),

Since, the random number generator starts from 0, and our image starts from “face1”, we add 1 to two variables.

So that, the random number generator starts from 1.

Inside the setState() method, we have used two variables. Subsequently, clicking one image changes both images. At the same time.

However, the change is random.

As mood swings, the images of faces also change in any direction representing different type of moods.

setState(() {
      leftFaceIndex = Random().nextInt(4);
      rightFaceIndex = Random().nextInt(4);
    });

In our previous sections we have learned that a function holds the same instructions so that we can reuse the function anywhere.

For that reason, we have put the setState() method inside a common function.

void changeMood() {
    setState(() {
      leftFaceIndex = Random().nextInt(4);
      rightFaceIndex = Random().nextInt(4);
    });
  }

And, finally, we call that changeMood() method inside the “onTap” property that expects an anonymous function. For two faces we have used twice the “VoidCallback”.

onTap: () {
  changeMood();
},

In the coming sections, we will take this knowledge from lesser known facts to unknown facts about the List and Map in Dart. And, after that, we will build the Flutter Quiz App.

Sp keep reading. Happy Fluttering.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

3 responses to “How to use Dart Math in Flutter”

  1. […] In any Flutter App, we will find function everywhere. Therefore, we need to understand how a function works. Moreover, what do we mean by a function. […]

  2. […] us refactor the “Mood Swing App” and make it more reusable and […]

  3. […] us refactor the “Mood Swing App” and make it more reusable and […]

Leave a Reply