📅  最后修改于: 2023-12-03 14:40:36.618000             🧑  作者: Mango
Dart is a powerful programming language that allows developers to perform a wide range of tasks. One of the most common tasks that developers need to perform is printing the items in a list. In this article, we will explore how to print the item number of a list in Dart.
To print the item number of a list in Dart, we can use the forEach
method. This method applies a given function to each element of the list in turn. Here is an example:
void main() {
final List<String> fruits = ['apple', 'banana', 'kiwi', 'mango'];
fruits.forEach((String fruit) {
final int index = fruits.indexOf(fruit) + 1;
print('$index. $fruit');
});
}
In this example, we first create a List
called fruits
which contains four String elements. We then call the forEach
method on fruits
, passing in a function that takes a String
argument called fruit
.
Within the function, we first get the index of the current fruit
in the list using the indexOf
method. Since the index of the first element in a list is 0, we add 1 to get the item number. We then print the item number and the fruit
using the print
statement.
When we run this code, we get the following output:
1. apple
2. banana
3. kiwi
4. mango
This code is a simple example of how to print the item number of a list in Dart. It can be easily modified to suit different use cases and applications.
Printing the item number of a list is a common task in programming. With Dart, developers can easily accomplish this task using the forEach
method. This method allows developers to apply a given function to each element of a list in turn, making it simple to print the item number alongside the list item.