Please I'm need clarification on what the Map funtion and spread function does in flutter.
...(questions[questionIndex]['answers'] as List<String>).map((answer) {
return Answer(selectHandler: answerQuestion, answerText: answer);}).toList()
In the code above, I have Question map with keys and values, but the transformation process of the list to widget using map function with spread indicated by three dots, is what I need clarification on. Please someone help me explain to me. Thanks.
Also is there any other recommendation on transforming list to wiidget without using map function?
CodePudding user response:
the spread operation let you combine a List
element inside another List
, it's like you say: "merge the elements of that spread list into the main list".
example :
list<int> list1 = [1, 2, 3];
list<int> list2 = [4, 5, 6];
list<int> margeOfElementsOfLists = [...list1, ...list2];
print(margeOfElementsOfLists); // [1,2,3,4,5,6]
in the other hand, the map
method is not related directly to the Map
object in dart.
it gives you the ability to get a copy of the original list with executing a kind of function on all elements, taking the previous list :
print(margeOfElementsOfLists.map((number) => number *2).toList()); // [2,4,6,8,10,12]
so in your case, it's like you're saying, for all elements, create a widget that takes the answer as property and makes from it an Answer
widget, then merge the elements of that list inside of the main List
, which can be the children List
of a Row
or Column
CodePudding user response:
I am beginner in flutter...so far I have noticed that map is easy to use than other looping...
I had a created a demo regarding it
here it is ...if it might help u
class MyApp extends StatelessWidget {
MyApp({Key? key}) : super(key: key);
List<int> numbers = [3, 5, 2, 4, 5, 6, 2];
List<Widget> int_to_widgetlist() {
// using map u can code as per following
//return numbers.map((e) => Text(e.toString())).toList();
// or u can use for loop or any other loop
List<Widget> widgetlist = [];
for (int x = 0; x < numbers.length; x ) {
widgetlist.add(Text(numbers[x].toString()));
}
return widgetlist;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Column(
children: int_to_widgetlist(),
),
),
);
}
}
and about spread operator its is like
var list = [1, 2, 3];
var list2 = [0, ...list];