Trusted answers to developer questions

How to create an array in Dart

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

An array is an object used to store a collection of values. This collection could be anything: numbers, objects, more arrays, etc.

In Dart, arrays are used to store multiple values in one variable. Each value can be accessed through an index (starts from zero). The values stored in an array are called elements.

svg viewer

Initializing arrays in Dart

There are multiple ways to initialize arrays in Dart:

1. Using the literal constructor

A new array can be created by using the literal constructor []:

import 'dart:convert';
void main() {
var arr = ['a','b','c','d','e'];
print(arr);
}

2. Using the new keyword

An array can also be created using new along with arguments:

import 'dart:convert';
void main() {
var arr = new List(5);// creates an empty array of length 5
// assigning values to all the indices
arr[0] = 'a';
arr[1] = 'b';
arr[2] = 'c';
arr[3] = 'd';
arr[4] = 'e';
print(arr);
}

A few commonly used methods

Method Description
first() It returns the first element of the array.
last() It returns the last element of the array.
isEmpty() It returns true if the list is empty; otherwise, it returns false.
length() It returns the length of the array.
import 'dart:convert';
void main() {
var arr = ['a','b','c','d','e'];
print(arr.first);// first element of array
print(arr.last);// last element of array
print(arr.isEmpty);// to check whether the array is empty or not
print(arr.length);// the lenght of the array
}

RELATED TAGS

basics
dart
array
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?