0

How to create Multidimensional List in dart?. IN other languages we can use array for this But in dart we use List . SO i find in google I could not found method for Create Multidimensional List in dart ? Anyone Know create Multidimensional List in dart ?

1 Answer 1

2

There are multiple ways to accomplish that. The simplest solution is to create a list of lists like:

void main() {
  // Create 5x5 list
  List<List<int>> twoDimList = List.generate(5, (_) => List.filled(5, 0));
  twoDimList[0][0] = 5;
  print(twoDimList);
}

A more efficient way to do it is to use a single list and access it by using two coordinates like the following class I have used in a previous project:

class Grid<T> {
  final int length, height;
  final List<T> list;

  Grid(this.length, this.height) : list = List(length * height);

  T get(int x, int y) => list[_getPos(x, y)];
  void set(int x, int y, T value) => list[_getPos(x, y)] = value;

  int _getPos(int x, int y) => x + (y * length);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.