For loop Flutter: PriceTracker App – Step 1

Can we use for loop in Flutter? If we can, then how we can use for loop in Flutter? We’re going to see that in a minute. In addition, we will build a Price Tracker Flutter App which will use the for loop.

Because of that reason, we will first check how we can use for loop in Flutter to build a custom Drop down menu Item.

Why do we use for loop?

The first and foremost reason is to to repeat a specific block of code a known number of times.

As a result, we can start from 0 and stop at 4. And, in addition, we can print each number.

Consider the code below.

void main() {
  for (int i = 0; i < 5; i++) {
    print('hello ${i + 1}');
  }
}

/**
hello 1
hello 2
hello 3
hello 4
hello 5
 * 
 * 
 */ 

But, in Dart, and Flutter for loop can play another role.

What is that role?

The role is to iterate over the list of items. For that reason, we can use the for-in loop.

For example, consider the code as follows where we have used the for-in loop to iterate over a list of items.

void main() {
  
  List<String> firstNameList = ['John', 'Json', 'Dracula', 'Othelo'];
  
  List<String> secndNameList = ['Hamlet', 'Json', 'Hegemoto', 'Piku'];
  
  checkNames(firstNameList); // You have 2 number of same names.
  checkNames(secndNameList); // You have 1 number of same names.
 
}

 List<String> listOfNames = ['Macbeth', 'Othelo', 'Hamlet', 'John', 'Shakespeare'];

void checkNames(List<String> nameList) {
  
  int name = 0;
  
  for(String names in nameList){
    for(String matchingName in listOfNames) {
      if(names == matchingName){
        name++;
      }
          
    }
  }
  
  print('You have $name number of same names.');
}

The above code shows how we can read the items by using the for-in loop. After that, we can also check whether a common name exists or not.

The same way, we can create a drop down menu item widget using a constant list of items.

Since we are going to display the exchange rate of US dollar in different currency, we should display the list of currency first.

Let us see how it looks like.

For loop Flutter - PriceTracker App first
For loop Flutter – PriceTracker App first

Firstly, to show a list of currency like above we should create a list of currencies first.

We will keep that file in our model folder.

const List<String> currencyList = [
  'INR',
  'JPY',
  'MXN',
  'NOK',
  'NZD',
  'PLN',
  'RON',
  'BRL',
  'CAD',
  'CNY',
  'EUR',
  'GBP',
  'HKD',
  'IDR',
  'ILS',
  'RUB',
];

After that, we will create a custom drop down button method.

Why?

Because this method will keep the selected currency in a setState() method as a value that we can display.

For loop Flutter - PriceTracker App second
For loop Flutter – PriceTracker App second

We can see that the list starts with INR or Indian Rupees.

But at the same time we can choose any currency from the above list.

For loop Flutter - PriceTracker App third
For loop Flutter – PriceTracker App third

As the above image shows, we have chosen RUB or ruble.

How for loop in Flutter works?

It works just like any for-in loop. We iterate over the list of currencies that we have kept in the model folder.

DropdownButton<String> selectDropDownList() {
    List<DropdownMenuItem<String>> dropDownItems = [];
    for (String currency in currencyList) {
      var newItem = DropdownMenuItem(
        child: Text(currency),
        value: currency,
      );
      dropDownItems.add(newItem);
    }

    return DropdownButton<String>(
      value: selectedCurrency,
      items: dropDownItems,
      onChanged: (value) {
        setState(() {
          selectedCurrency = value!;
        });
      },
    );
  }

And, lastly we call this method in the bottom Container Widget.

As a result, when we select any currency, it will display the exchange rate.

import 'package:flutter/material.dart';
import '../model/usd_data.dart';

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

  @override
  _DisplayExchangerateInUSDState createState() =>
      _DisplayExchangerateInUSDState();
}

class _DisplayExchangerateInUSDState extends State<DisplayExchangerateInUSD> {
  String selectedCurrency = 'INR';

  DropdownButton<String> selectDropDownList() {
    List<DropdownMenuItem<String>> dropDownItems = [];
    for (String currency in currencyList) {
      var newItem = DropdownMenuItem(
        child: Text(currency),
        value: currency,
      );
      dropDownItems.add(newItem);
    }

    return DropdownButton<String>(
      value: selectedCurrency,
      items: dropDownItems,
      onChanged: (value) {
        setState(() {
          selectedCurrency = value!;
        });
      },
    );
  }

  String? value = '?';
 

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Price Tracker'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
            child: Card(
              color: Colors.redAccent,
              elevation: 5.0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              child: Padding(
                padding: const EdgeInsets.symmetric(
                    vertical: 15.0, horizontal: 28.0),
                child: Text(
                  '1 USD = $value $selectedCurrency',
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    fontSize: 20.0,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
          Container(
            height: 150.0,
            alignment: Alignment.center,
            padding: const EdgeInsets.only(bottom: 30.0),
            color: Colors.red,
            child: selectDropDownList(),
          ),
        ],
      ),
    );
  }
}

Finally, our goal is to use the API of the https://exchangeratesapi.io/ to display the exchange rate.

In that case, the drop down menu item will track the price.

We will discuss that part in our next step.

By that time if you want to clone this step, please use this GitHub repository.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

Leave a Reply