//Only the 2nd Class of the stateful widget is shown here
class _TestState extends State<Test> {
List<String> names = [
'Debanjan',
'Swarnava',
'Aishik',
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: names.map(
(name){
return Text(name);
}
).toList(),
),
);
}
}
We define a List of strings (names). Now we want to display the names.
Now two ways possible-
i) Hardcode those as widgets
ii) Display names taking them from the list.
The 2nd method is better, since if the list increases then we don’t have to hardcode it separately again.
So, we define the children values by mapping those with the list items, as names.map( ).
Inside names.map we define a variable to store the value of the element coming from the list at a time (here variable is name), then we define a function ( here one line function, return … ), using the variable just defined. The func. returns a text widget.
Now names.map() generates an iterable. But we have to supply the children property with a list. So, we use a method .toList( ) to convert the generated iterable into a list.
Remember? For a function, we can directly write in one line using =>
Column(
children: names.map((name)=>Text(name)).toList(),
),