📜  array 2d dart (1)

📅  最后修改于: 2023-12-03 14:39:20.817000             🧑  作者: Mango

2D Array in Dart

A 2D array in Dart is a list of lists. It is a way to store data in a grid-like structure, where each cell can hold one value.

Declaration
List<List<int>> array2D = List.generate(numOfRows, (i) => List(numOfColumns), growable: false);

The List<List<int>> is a list of lists, where the inner list is of type int. In the example above, numOfRows and numOfColumns are the number of rows and columns in the 2D array, respectively.

Using the List.generate() method, we can create a 2D array of a specified number of rows and columns. The growable parameter specifies whether the list can grow dynamically or not. In the example above, growable is set to false to prevent the list from growing dynamically.

Accessing Elements

We can access elements in a 2D array using the row and column indices. For example:

array2D[0][1] = 5; // sets the value at row 0, column 1 to 5
int value = array2D[2][3]; // gets the value at row 2, column 3
Iterating Over a 2D Array

We can iterate over each element in a 2D array using nested loops. For example:

for(int i = 0; i < numOfRows; i++) {
  for(int j = 0; j < numOfColumns; j++) {
    // do something with array2D[i][j]
  }
}
Conclusion

A 2D array is a useful data structure to store data in a grid-like structure. In Dart, we can declare a 2D array using List<List<T>> and access elements using row and column indices. We can also iterate over each element using nested loops.