What is a Flutter function example

To understand how function works in Flutter, we need to see some examples.

As we have been progressing, we have found that the “function” plays an important role in building any Flutter App.

With the help of a instance method, which is actually a function, we have already managed State without a Stateful Widget.

And to do that we used the “Provider” package. To make it work we had created a “Model” folder in the project directory and created an instance method, or a function.

Let us take a look at the code that we have used already in our previous “Mood Swing App”.

There was only one function – changeMood().

import 'dart:math';

import 'package:flutter/material.dart';

class Mood with ChangeNotifier {
  int leftFaceIndex = 1;
  int rightFaceIndex = 1;
  void changeMood() {
    leftFaceIndex = Random().nextInt(4);
    rightFaceIndex = Random().nextInt(4);
    notifyListeners();
  }
}

In the above code, we see a basic function changeMood() which is void. It does not take any input as arguments. It has called another function notifyListeners() and initialised two variables inside its code block.

In short, it just instructs to do some jobs.

To clarify, the basic function only gives simple instructions.

In fact, this is the most basic function example in Flutter.

We can see the same code in Dart console also to understand how it works.

/// this is the most basic of all functions
/// where we give instructions and call the function name

void main() {
  
 printStatement(); // Printing statement.
  
}


void printStatement() {
  print('Printing statement.');
}

Although it is the most basic function example, we should not underestimate its importance or power. Sometimes in Flutter we need to give a lot of instructions. Thus, we keep those instructions inside a function body. After that, we call the function when we need those instructions to be carried out.

Why?

Because, while building Flutter Applications we will find a lot of implementation of such basic functions.

These functions does not return any data type. Neither they take inputs as its arguments. But they call other functions, initialise variables and that might add more features to our Flutter App.

Consider the previous “Mood Swing App”. As users tap any image of face, it changes the State of the associated Image Widget. As a result, we see that one face is replaced by another face. As our mood changes, subsequently our facial expression also changes.

However, we can add a Text Widget below each Image Widget. As a result, clicking image changes the color of the Text change subsequently.

Let us see how we can accomplish that task.

Firstly, we can add one more simple function, or instance method in the Mood Class.

Why?

The reason is simple.

We can provide the same data Type with the help of the “Provider” package.

Therefore, let us change the Mood Class as follows.

import 'dart:math';

import 'package:flutter/material.dart';

class Mood with ChangeNotifier {
  int leftFaceIndex = 1;
  int rightFaceIndex = 1;

  List colors = [Colors.red, Colors.green, Colors.purple, Colors.deepOrange];
  int leftIndex = 1;
  int rightIndex = 1;

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

  void changeColor() {
    leftIndex = Random().nextInt(4);
    rightIndex = Random().nextInt(4);
    notifyListeners();
  }
}

We have added one new function, or instance method – changeColor().

This is just another most basic function example in Flutter.

What will this function in Flutter do?

With the help of Dart Math library it will randomise the color of the Text Widget. As you can see, we have made a list of four colours – red, green, purple and deep orange.

As users tap any image, consequently two images will change and with that the color of the Text will also change.

Let us see how it works. We click any image below and see what happens next.


Flutter function first example
Flutter function first example

As we click any image below, it will not only change both faces, but change the associated colours also.

Meanwhile it proves that the most basic function in Flutter possesses a lot of power.


Flutter function second example
Flutter function second example

If you go on clicking, it will generate different faces and colours at the same time.

Now we can access these two functions, and properties just like before. To do that, we use the “Provider” package.

Let us see the full code.

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';

import '../model/mood.dart';

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

  @override
  Widget build(BuildContext context) {
    final mood = Provider.of<Mood>(context);
    final color = Provider.of<Mood>(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: () {
                    mood.changeMood();
                    color.changeColor();
                  },
                  child: Column(
                    children: [
                      Image.asset('images/face${mood.leftFaceIndex + 1}.jpg'),
                      Container(
                        padding: const EdgeInsets.all(5.0),
                        child: Text(
                          'Mood Changes with Color',
                          style: GoogleFonts.laila(
                            textStyle: Theme.of(context).textTheme.headline6,
                            fontSize: 20,
                            fontWeight: FontWeight.w700,
                            color: color.colors[color.leftIndex],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    mood.changeMood();
                    color.changeColor();
                  },
                  child: Column(
                    children: [
                      Image.asset('images/face${mood.rightFaceIndex + 1}.jpg'),
                      Container(
                        padding: const EdgeInsets.all(5.0),
                        child: Text(
                          'Mood Changes with Color',
                          style: GoogleFonts.laila(
                            textStyle: Theme.of(context).textTheme.headline6,
                            fontSize: 20,
                            fontWeight: FontWeight.w700,
                            color: color.colors[color.rightIndex],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

However, if you want to clone the whole project in your machine please visit this branch of GitHub Repository.

Moreover, in the next two sections, we will discuss two more function examples in Flutter.

We will see, how those types of functions work in our Flutter App.

So keep reading and 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 “What is a Flutter function example”

  1. […] like Mathematics, in Flutter function is everywhere. As a result, we cannot think Mathematics without function. And the same is true for […]

  2. […] have already discussed two kinds of functions. The first kind is simple. It places a set of instructions inside the function body. When we call the function, the instructions are carried out. The second kind takes inputs making […]

  3. […] have already discussed two kinds of functions. The first kind is simple. It places a set of instructions inside the function body. When we call the function, the instructions are carried out. The second kind takes inputs […]

Leave a Reply