dart

Dart Collections - Create a List or Array

In dart, List is a collection of one or more items that can be accessed using index.

void main() {
    //Direct assign values
    final listOfStrings = ['one', 'two', 'three'];
    print(listOfStrings);

    final listOfInts = [1, 2, 3];
    print(listOfInts);

    // Specify type then assign values
    var listOfStrings2 = <String>[];
    listOfStrings2 = ['item 1', 'item 2'];
    print(listOfStrings2);
  
   // create list using List keyword
   List<String> list3 = [];
   list3.add("item 1");
   print(list3);
}

Syntax

The basic syntax to create list in dart is as below

List<variable_type> varName = [];

//or
var myList = <String>[];

Get list items using index

void main() {
    final myList = ["One", "Two", "Three"];
    print(myList[1]); // -> prints "Two"
}

Create list of multiple sets

void main() {
  final listOfSets = [
    {"id": 1, "name": "John"},
    {"id": 2, "name": "Rick"},
    {"id": 2, "name": "Carol"}
  ];

  print(listOfSets[0]);

  for(var item in listOfSets) {
    print(item);
  }
}

Output

{id: 1, name: John}
{id: 1, name: John}
{id: 2, name: Rick}
{id: 2, name: Carol}
Was this helpful?