For loop 初始化Dart中的列表列表
我在Dart中实现了一个网格,如下所示:For loop 初始化Dart中的列表列表,for-loop,dart,closures,For Loop,Dart,Closures,我在Dart中实现了一个网格,如下所示: class Cell { int row; int col; Cell(this.row, this.col); } class Grid { List<List<Cell>> rows = new List(GRID_SIZE); Grid() { rows.fillRange(0, rows.length, new List(GRID_SIZE)); } }
class Cell {
int row;
int col;
Cell(this.row, this.col);
}
class Grid {
List<List<Cell>> rows = new List(GRID_SIZE);
Grid() {
rows.fillRange(0, rows.length, new List(GRID_SIZE));
}
}
但由于Dart的关闭错误保护功能,我的网格最终被行
成员中的网格大小为-1
的单元格填充
那么,Dart中初始化嵌套列表的惯用方法是什么呢?我想这就是您想要的:
class Grid {
List<List<Cell>> rows; // = new List(GRID_SIZE);
Grid() {
rows = new List.generate(GRID_SIZE, (i) =>
new List.generate(GRID_SIZE, (j) => new Cell(i, j)));
}
}
类网格{
列表行;/=新列表(网格大小);
网格(){
行=新列表。生成(网格大小,(i)=>
生成(网格大小,(j)=>新单元(i,j));
}
}
另见
class Grid {
List<List<Cell>> rows; // = new List(GRID_SIZE);
Grid() {
rows = new List.generate(GRID_SIZE, (i) =>
new List.generate(GRID_SIZE, (j) => new Cell(i, j)));
}
}