What is for loop in Flutter

In Flutter, as a cross-platform UI toolkit, for loop plays a crucial role in creating dynamic and flexible user interfaces. They enable developers to generate multiple widgets with varying properties or data, making it easier to build complex layouts and display dynamic content.

Syntax

The basic syntax of a for loop in Flutter is as follows:

for (int k = 0; k < collection.length; k++) {
// code to be executed on each item
}

Explanation

  • Initialization: The for loop in Flutter begins with the keyword for and is enclosed in parentheses (), where we define a loop counter variable, such as k. The counter variable is initialized to a starting value, typically 0 when the loop commences.

  • Condition: The loop condition is checked before each iteration. For instance, if the condition "k < collection.length" is met, the loop will continue executing until the counter variable k is no longer less than the length of the collection.

  • Update: The increment statement k++ is executed after each iteration, increasing the value of the counter variable k by 1 in each step.

Using for loop to create a list of widgets

We can use a for loop inside the children property of the Column widget to make Text widgets without creating a new Text widget manually ten times. The code example below explains the process.

Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (int k = 0; k < 10; k++)
Text("Text Widget Number $k"),
],
),

Output

The code example of a function below explains how we can wrap the Text widget inside a Container widget and make a list of it to return into a Column widget:

List<Widget> _buildTextWidgets( ) {
List<Widget> textWidgets = []; // Add an empty Container as a default widget
for (int k = 0; k < 10; k++) {
textWidgets.add(
Container(
width: 300,
height: 50,
child: Card(
child: Text("Item $k"),
),
), // ending bracket of container
); // ending bracket of add function
} // ending bracket of for loop
return textWidgets;
} // ending bracket of function

Code explanation

  • Line 1: This line defines a private function named _buildTextWidgets that returns a list of widgets List<Widget>. The function does not take any arguments.

  • Line 2: This line declares and initializes an empty list named textWidgets. This list will store the widgets created inside the for loop.

  • Line 3: This line starts a for loop that will execute ten times. It initializes an integer variable k with the value of 0. It will keep running as long as k is less than 10. In each iteration, k will be incremented by 1.

  • Line 4: This line adds a new widget to the textWidgets list in each iteration.

  • Line 5: This line declares a Container widget, which creates a rectangular visual element.

  • Lines 8–9: This line declares a Card widget. The Card widget will act as a parent for the Text widget. The text displayed by the Text widget will be "Item 0" for the first iteration, "Item 1" for the second iteration, and so on until "Item 9" for the last iteration. The $k is an interpolated value that inserts the current k value into the string.

  • Line 14: This line returns the textWidgets list, which now contains the widgets created inside the for loop.

Now we can call the function declared above _buildTextWidgets into the Column widget using the code given below:

Column(
children: _buildTextWidgets(),
),

Complete code

We get the following output by putting together the code explained above.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  List<Widget> _buildTextWidgets( ) {
    List<Widget> textWidgets = []; // Add an empty Container as a default widget
    for (int k = 0; k < 10; k++) {
      textWidgets.add(
        Container(
          width: 300,
          height: 50,
          child: Card(
            child: Text("Item $k"),
          ),
        ), // ending bracket of container
      ); // ending bracket of add function
    } // ending bracket of for loop
    return textWidgets;
  } // ending bracket of function

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Educative For Loop Answers'),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: _buildTextWidgets(), 
        ),
      ), // ending bracket of for Scaffold
    );// ending bracket of for Material App
  } // ending bracket of for build
}// ending bracket of for class

Output

After running the above code, we can see the following output.

Conclusion

The for loop in Flutter is a powerful control flow mechanism that allows developers to generate dynamic and flexible user interfaces. Using the for loop, developers can efficiently create widgets and customize them based on specific requirements, saving time and reducing repetitive code. This capability enhances the overall development process and contributes to building engaging and interactive Flutter applications with ease.

Copyright ©2024 Educative, Inc. All rights reserved