In this example, we are going to show you how to use for loop on widgets like row, column, wrap, and stack children. For loop is the basic loop in every programming language, Flutter also has features to use For loop to build your widgets, see the example below:
Column(
children: [
for(int x = 1; x<=5;x++)...[
Container(
child: Text("$x")
),
],
],
)
You can use For a look like above, you can add your own additional widgets before and after this loop as well.
Alternatively, you can build a list of widgets before building widgets and pass it on to children attribute like below:
@override
Widget build(BuildContext context) {
List<Widget> mywidgets = [];
for(int x = 1; x<=5;x++){
mywidgets.add(
Container(
child: Text("$x"),
)
);
}
return Scaffold(
body: Container(
child: Column(
children: mywidgets
)
)
);
}
The output of both codes will be the same.
import 'package:flutter/material.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget{
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("For Loop in Widget Children"),
backgroundColor: Colors.redAccent,
),
body: Container(
child: Column(
children: [
//you can add widgets here also
for(int x = 1; x<=5;x++)...[
Card(
child: Container(
padding: EdgeInsets.all(10),
width: double.infinity,
child:Text("Item $x"),
)
),
// you can add widget here as well
],
// you can add more widgets here
],
),
)
);
}
}
In this way, you can use For loop in Widget's children in Flutter.
Please Wait...
No any Comments on this Article