Flutter Business Logic: Happiness App – Final Step

We have reached the final stage. So we will use the Flutter Business Logic and finish our Happiness Calculator App.

While building the Flutter App, we have learned a few key concepts.

Firstly, we have learned how to use enum. Secondly, we have learned ternary operator. Thirdly, we have grasped how to customize the Slider theme.

Further, we have absorbed the basic route mechanism.

If you are a beginner, please follow the steps and clone the GitHub repository. In fact, you will find them in the step-by-step branches.

Please clone them and test in your local machine.

What is the difference between Business Logic and UI Logic?

Flutter is a cross-platform Framework or UI toolkit. What does that mean? It means the user interface plays an important role.

Each time Flutter calls the build() method the old instance of Widget destroys itself. As a result, the Widget rebuilds itself and a new instance shows up.

Flutter mostly handles the UI logic. Therefore, we do not have to bother. We just extends either Stateless, or a Stateful Widget. And, we move on.

Of course, Flutter allows us to create our own Widget. Quite naturally. Because Flutter is open source and we get the source code in GitHub.

However, we need to create our Business Logic. As it happens in our Happiness Calculator App.

In the previous section we have seen that the Result page displays some static Text output. Right?

Take a look at the last stage where we have left.

Navigation Flutter_ result page
Navigation Flutter_ result page

The above page does not reflect the dynamic properties that should have come from the home page.

A user will set the “greed” factor to a number. In respect to that she will also have to choose two other factors, such as “gratitude” and “diligence”.

Subsequently, our home page will store those values somewhere and our business logic will decide whether the user is happy or unhappy.

Moreover, based on that, the Flutter Business Logic will also advise what to do. This mechanism will ensure code separation.

Why?

Because it is important for clean architecture.

How to create Flutter Business Logic?

The algorithm is simple. We have seen that greed has a minimum value 20. Because we all come to this planet with some in-built greed. The maximum value is 100.

The same is true for other two factors. The “gratitude” and “diligence” also have some minimum values. Subsequently, the user can increase or decrease the value.

Here, our business logic is simple. Firstly, we combine the values of the “gratitude” and “diligence”. Secondly, we subtract the value of “greed” from it.

The result is the happiness index value.

Let us see the code.

class HappinessCalculator {
  final int? greed;
  final int? gratitude;
  final int? diligence;

  int? _happinessIndex;

  HappinessCalculator({
    required this.greed,
    required this.gratitude,
    required this.diligence,
  });

  String calculateHappiness() {
    _happinessIndex = (gratitude! + diligence!) - greed!;
    return _happinessIndex.toString();
  }

  String getResult() {
    if (_happinessIndex! <= 50) {
      return 'Unhappy';
    } else {
      return 'Happy';
    }
  }

  String getAdvice() {
    if (_happinessIndex! <= 50) {
      return 'Please reduce greed and increase gratitude and dligence.';
    } else {
      return 'You are a Happy person. Study old philosophers, and stay cool.';
    }
  }
}

In the above code, if happiness index is equal and lower than 50, you are unhappy. However, if the happiness index is greater than 50, then you are happy.

The real challenge is elsewhere.

We need to pass these values to the result page.

How to pass values through Navigation?

In our previous section we have finished the design part and learned how to navigate to the result page.

Therefore, we are not going to repeat the full code of the Happiness App home page.

We will take a look at the bottom navigation bar part where we have handled the business logic.

bottomNavigationBar: Container(
        width: double.infinity,
        height: 60.0,
        color: HappyTheme.activeCoor,
        child: TextButton(
          onPressed: () {
            HappinessCalculator happy = HappinessCalculator(
              greed: greed,
              gratitude: gratitude,
              diligence: diligence,
            );
            happy.calculateHappiness();
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => HappinessResult(
                  greed: greed,
                  gratitude: gratitude,
                  diligence: diligence,
                  happinessIndex: happy.getResult(),
                  whatIsToBeDone: happy.getAdvice(),
                ),
              ),
            );
          },
          child: Text(
            'CALCULATE',
            style: HappyTheme.appbarStyle,
          ),
        ),
      ),

In the above code, what do we see?

Firstly, we have created a HappinessCalculator object. After that, we call the calculateHappiness() method that returns the happiness index.

String calculateHappiness() {
    _happinessIndex = (gratitude! + diligence!) - greed!;
    return _happinessIndex.toString();
  }

Now, we can pass that value to the result page through class constructor.

MaterialPageRoute(
                builder: (context) => HappinessResult(
                  greed: greed,
                  gratitude: gratitude,
                  diligence: diligence,
                  happinessIndex: happy.getResult(),
                  whatIsToBeDone: happy.getAdvice(),
                ),
              ),
            );

For that reason, now it becomes easier for us to display these values in the result page.

Suppose the user has more greed and less gratitude and diligence.

The home page will look as follows.

Flutter Business Logic to calculate Happiness index
Flutter Business Logic to calculate Happiness index

When you have more greed, it overshadows every virtue.

As a result, the user becomes unhappy. But at the same time, we can see the values on the result page.

Flutter Business Logic calculates and finds the reasons of unhappiness
Flutter Business Logic calculates and finds the reasons of unhappiness

The result clearly shows why the user is unhappy. The reason is simple. The user has greed 69, and on the contrary, gratitude is 10, and diligence is 39.

However, if the user has less greed but more gratitude and diligence?

The result page changes the values and displays them.

Flutter Business Logic to calculates and finds out why the user is happy
Flutter Business Logic calculates and finds out why the user is happy

How we can display data got from Business Logic?

It is not at all difficult. On the contrary, it is quite simple.

Because Flutter framework allows us to pass those data through class constructor.

Let us take a look at the result page code.

import 'package:flutter/material.dart';
import 'package:happiness_calculator/model/happy_theme.dart';

class HappinessResult extends StatelessWidget {
  const HappinessResult({
    Key? key,
    required this.greed,
    required this.gratitude,
    required this.diligence,
    required this.happinessIndex,
    required this.whatIsToBeDone,
  }) : super(key: key);
  final int greed;
  final int gratitude;
  final int diligence;

  final String happinessIndex;
  final String whatIsToBeDone;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: HappyTheme.shrineBrown900,
      appBar: AppBar(
        backgroundColor: HappyTheme.shrineBrown600,
        title: Text(
          'How Happy You Are!',
          style: HappyTheme.appbarStyle,
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(18.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              margin: const EdgeInsets.all(15.0),
              child: Text(
                'Result: Your Greed is: $greed, '
                'your Gratitude is: $gratitude '
                'your Diligence is: $diligence.',
                style: HappyTheme.resultStyle,
              ),
            ),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.only(
                top: 10.0,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    happinessIndex,
                    style: HappyTheme.happinessIndexStyle,
                  ),
                  const SizedBox(
                    height: 10.0,
                  ),
                  Text(
                    whatIsToBeDone,
                    style: HappyTheme.happinessResultStyle,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: Container(
        width: double.infinity,
        height: 60.0,
        color: HappyTheme.activeCoor,
        child: TextButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text(
            'RE-CALCULATE',
            style: HappyTheme.appbarStyle,
          ),
        ),
      ),
    );
  }
}

The above code shows us how the result page gets the values through class constructors.

In addition, we can display them in Text Widgets. How? Because in our business logic, we return String data type.

For brevity, we have avoided to show full code. But, if you want to clone the final project, please visit this GitHub rpository.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

One response to “Flutter Business Logic: Happiness App – Final Step”

  1. […] our previous Flutter App, “Happiness Calculator”, we have seen how we can use simple […]

Leave a Reply