How to use variable in Flutter

Previously we have discussed variable in Dart Programming language. What we have seen? A variable is like a container that contains a certain “Type” of value. When we use variable in Flutter, we must remember that core principle.

Why?

The Dart Programming language is “Statically Typed”. That means, when we declare a variable, we should specify the “Type”.

A beginner may get confused in this part.

Therefore, we need to clarify this concept a little further.

As we said, a variable acts like a container. Consider the following example.

String name;

The name of the variable is “name”, and the type is String.

As a result, we cannot write like this anymore.

name = 10; // this will throw an error

We need to understand this concept. The variable “name” only can contain String type of value.

Even if we write like this:

var name = 'John';

Even after that, we cannot put any other value inside the container “name”.

name = 10; // we cannot do this, it will again throw an error

Now, you may ask, why this happens? We have not mentioned any type before the variable “name”. We have used the keyword “var”.

How Dart knows that it should be a String?

Basically, it happens because Dart automatically infers when we initialise the variable with a certain “Type”.

In the above case, we have initialised the variable with a String value.

Right?

However, consider the following code. Also read the comments. That will explain everything.

void main() {
  // Dart is statically typed language
  var name = 'Sanjib';
  print('Name is $name');
  
  // we cannot assign any other type to the variable name
  // name = 1; 
  // A value of type 'int' can't be assigned to a variable of type 'String'.
  
  // now it makes dynamically typed which is not recommended
  var age; 
  // Prefer typing uninitialised variables and fields.
  age = 100;
  print('Age is: $age'); 
  
  age = 'Age';
  print('Age is: $age');
  
  /**
OUTPUT:
   Name is Sanjib
Age is: 100
Age is: Age
   * 
   * */
  
}

When we do not initialise a variable or a field, we must declare the Type.

Do not write like this.

var age;

Although the name of the variable suggests that it should be an Integer type, but we can change the value anytime. Basically, the Dart programming language also has a type “dynamic”.

If we do not initialise a variable, and use a keyword “var”, then it becomes “dynamically typed”.

However, it is not recommended.

Dart wants us to maintain the “Type” all through the life cycle of the code. It guarantees type safety. If we inadvertently change the type, Dart will complain. And we will rectify the error instantly.

How do you set variables in flutter?

We can set variables in Flutter according to the rule we have just mentioned.

If we know that we are going to use a text, we should initialise the variable with a String value.

Consider the following example.

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {

    String greedy = 'greedy';
    String confident = 'confident';
    String careLess = 'careless';

    return Scaffold(
      backgroundColor: Colors.white70,
      appBar: AppBar(
        title: const Text('Anonymous Function Example'),
      ),
      body: Center(
        child: Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    print('I am Greedy 3D Buddy.');
                  },
                  child: Image.asset('images/$greedy.jpg'),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    print('I am Confident 3D Buddy');
                  },
                  child: Image.asset('images/$confident.jpg'),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    print('I am Careless 3D Buddy.');
                  },
                  child: Image.asset('images/$careless.jpg'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

As a result, we can run the Flutter App, and get the output just like before.

It happens because the Image.asset() named constructor passes a String value.

Anonymous function Example in Flutter
Anonymous function Example in Flutter

Just like before, we can click any image and get the same output on the terminal.

However, we can reduce the code lines drastically. How? We can put all the variables inside a List.

Let us see the code snippet.

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    
    List name = ['greedy', 'confident', 'careless'];

    return Scaffold(
      backgroundColor: Colors.white70,
      appBar: AppBar(
        title: const Text('Anonymous Function Example'),
      ),
      body: Center(
        child: Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    print('I am Greedy 3D Buddy.');
                  },
                  child: Image.asset('images/${name[0]}.jpg'),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    print('I am Confident 3D Buddy');
                  },
                  child: Image.asset('images/${name[1]}.jpg'),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    print('I am Careless 3D Buddy.');
                  },
                  child: Image.asset('images/${name[2]}.jpg'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

The index of any List starts from 0. So this code refers to the correct name.

As a result, the Image.asset() named constructor gets the proper String value.

child: Image.asset('images/${name[0]}.jpg'), // greedy

Run the Flutter App, it will give the same output on the screen.

If we click any image, it will give the same output on the terminal.

Now, based on the above code, we can build an interesting Flutter App in the next section.

Stay tuned. Happy Fluttering.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter


Posted

in

, , ,

by

Comments

4 responses to “How to use variable in Flutter”

  1. […] is the role of variable in Flutter? In the previous section we have seen that. However, the demonstration was simple. We cannot change […]

  2. […] can store that value in a variable, pass the value as parameter or return the value from a […]

  3. […] With if-else, you cannot do that. You cannot assign the value of an if-else logic-tree to a variable. […]

  4. […] can store that value in a variable, pass the value as parameter or return the value from a […]

Leave a Reply