A list is a way of storing data in a list of order. In other programming, languages like PHP and javascript Array is used as a list.
List format:
List<dataType_of_this_list_element> myList = [element1, element2];
HOW TO CREATE EMPTY LIST IN DART?
List<String> myEmptyList =[];
HOW TO ADD ELEMENT TO THE END OF A LIST
list has add()
method which adds element at the end of a list.
List<String> myNewColors =["red", "yellow"];
myNewColors.add("white");
print(myNewColors);
/* Result:=>
[red, yellow, white]
*/
HOW TO REMOVE AN ELEMENT FROM A LIST
List<String> newColors =["red", "yellow"];
newColors.remove("yellow"); // remove "yellow" from the list
print(newColors);
/* Result:=>
[red]
*/
HOW TO Map Through A List
List<String> myColors =["red", "yellow"];
myColors.map((myColorsElement){ //"myColorsElement" represent each single elemnet in mycolors eg. "red" and "yellow"
// whatever code in this block will be run on each element in the list
print(myColorsElement); // print all the element
}).toList(); // don’t forget to convert it to a list
/* Result:=>
yellow
red
*/
HOW TO PRINT THE LAST ELEMENT OF A LIST TO THE FIRST
List<String> colors =["red", "yellow", "pink", "blue"];
/* first assign "i" the last index of the list length, then stop the loop when it's equals to 0 which represent the first element in the list.
Then decrease "i" since its starting from the end of the list */
for(int i=colors.length-1; i>=0; i--){
print(colors[i]);
}
/* Result:=>
blue
pink
yellow
red
*/
HOW TO CREATE A LIST THAT CONTAINS ANOTHER LIST
// from below, the list contains another list.
List<List<int>> myListOfLists = [[1, 2, 3], [4, 5, 6]];
// you need to first map through the parent list, then get the inner list and map through it too to get it element
myListOfLists.map((myInnerList){
myInnerList.map((innerListElement) {
print(innerListElement);
}).toList();
}).toList();
/* Result=>
1
2
3
4
5
6
*/
HOW TO CREATE A LIST REPRESENTATION OF MAP OR CONVERT LIST TO MAP
List<String> sports = ['cricket', 'football', 'tennis', 'baseball'];
// the key will be the index of the element in the list, and the value will be the element
Map<int, String> map = sports.asMap();
print(map); // {0: cricket, 1: football, 2: tennis, 3: baseball}
HOW TO SKIP ELEMENTS IN A LIST
// skip(index) means ignore all the element before this index, and then print the index element and all the element after it
List<String> colors =["red", "yellow", "pink", "blue"];
var bb =colors.skip(2);
print(bb);
// Result: (pink, blue)