{

Dart| Flutter How to: Insert an element at beginning of a List with Example


This tutorial shows how to insert the data at beginning of a list with examples in dart

List inserts the elements in the insertion order. In the below program, add method inserts the elements to the end of a List.

void main() {
  List wordsList = ['one', 'two', 'three'];
  wordsList.add("five");
  print(wordsList);
}

Output:

[one, two, three, five]

Dart List insert at the beginning with examples

List insert method provides inserting an element at the index position. with this method, It increases the size of the list and the list must be growable.

void insert(int index, dynamic element)
void main() {
  List wordsList = ['one', 'two', 'three'];
  wordsList.insert(0,"five");
  print(wordsList);
}

Output:

[five, one, two, three]

Similarly, you can add at the start of a list using another way using for-in loop syntax

void main() {
  List wordsList = ['one', 'two', 'three'];
  wordsList = [
    "five",
    for (String item in wordsList) item,
  ];
  print(wordsList);
}

Output:

[five, one, two, three]
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example