Chrome Extension

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);
}
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

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}

Search Index Data (The code snippet can also be found with below search text)

Create array in dart
Was this helpful?
0 Comments