Adding to a List: insert
Part of the Logic & Flow section of Coddy's Dart journey — lesson 4 of 65.
When you need to add an element to a specific position in a list, the insert() method gives you precise control over where the new element goes. Unlike the add() method, which always adds elements to the end of a list, insert() allows you to place an element at any position you choose.
The insert() method takes two parameters: the index position where you want to insert the element, and the element itself. When you insert an element, all existing elements at that position and beyond shift one position to the right.
List<String> tasks = ['Buy groceries', 'Walk the dog', 'Read a book'];
// Insert a new task at the beginning (index 0)
tasks.insert(0, 'Check emails');
print(tasks); // ['Check emails', 'Buy groceries', 'Walk the dog', 'Read a book']This method is particularly useful when the order of elements matters, such as priority lists, schedules, or any situation where you need to maintain a specific sequence. The ability to insert at any position makes insert() a powerful tool for managing ordered collections.
Challenge
EasyCreate a program that manages a priority task system by inserting urgent tasks at specific positions in an existing task list. Your program should:
- Read a string input representing the task list name
- Read multiple string inputs representing existing tasks (the input will end when you receive an empty string)
- Read a string input representing an urgent task to insert
- Read an integer input representing the position where the urgent task should be inserted
- Use the
insert()method to add the urgent task at the specified position - Print the updated task list in the exact format shown below
For example, if the task list name is "Work Schedule", the existing tasks are "Review documents", "Team meeting", "Submit report", the urgent task is "Client call", and the position is 1, your program should output:
Task List: Work Schedule
Original tasks: [Review documents, Team meeting, Submit report]
Inserted: Client call at position 1
Updated tasks: [Review documents, Client call, Team meeting, Submit report]
Total tasks: 4If the task list name is "Daily Goals", the existing tasks are "Exercise", "Read book", the urgent task is "Buy groceries", and the position is 0, your program should output:
Task List: Daily Goals
Original tasks: [Exercise, Read book]
Inserted: Buy groceries at position 0
Updated tasks: [Buy groceries, Exercise, Read book]
Total tasks: 3Your program must use the insert() method to add the urgent task at the specified position. The position input will always be a valid index (between 0 and the length of the existing task list).
Cheat sheet
The insert() method allows you to add an element at a specific position in a list. It takes two parameters: the index position and the element to insert.
List<String> tasks = ['Buy groceries', 'Walk the dog', 'Read a book'];
// Insert at index 0 (beginning)
tasks.insert(0, 'Check emails');
print(tasks); // ['Check emails', 'Buy groceries', 'Walk the dog', 'Read a book']When you insert an element, all existing elements at that position and beyond shift one position to the right. This method is useful for maintaining ordered collections where position matters.
Try it yourself
import 'dart:io';
void main() {
// Read task list name
String? taskListName = stdin.readLineSync();
// Read existing tasks until empty string
List<String> tasks = [];
while (true) {
String? task = stdin.readLineSync();
if (task == null || task.isEmpty) {
break;
}
tasks.add(task);
}
// Read urgent task and position
String? urgentTask = stdin.readLineSync();
int position = int.parse(stdin.readLineSync()!);
// TODO: Write your code below
// Use the insert() method to add the urgent task at the specified position
// Print the results in the required format
print('Task List: $taskListName');
print('Original tasks: $tasks');
print('Inserted: $urgentTask at position $position');
// Print updated tasks and total count
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List