Skip to main content

Exercise Overview

This exercise demonstrates how to work with Lists in Dart using functions. You’ll learn to:
  • Create and populate lists with user input
  • Pass lists to functions
  • Iterate through lists and display their contents

Problem Statement

Create a program that:
1

Create an empty list

Initialize an empty list of integers
2

Get user input

Use a function to ask the user for 10 integer values and add them to the list
3

Display the list

Use another function to print each element of the list

Solution Approach

Function 1: Getting User Input

This function receives a list, populates it with 10 user-provided integers, and returns the modified list:
When you pass a list to a function in Dart, you’re passing a reference to the list. This means modifications inside the function affect the original list.

Function 2: Displaying the List

This function iterates through the list and prints each value:
The for-in loop is perfect for iterating through all elements in a collection when you don’t need the index.

Main Function

The main function coordinates the program flow:

Complete Program

Key Concepts

List Declaration

List<int> numeros = [] creates an empty list of integers

Adding Elements

Use .add() method to append elements to a list

For-In Loop

for (var item in list) iterates through each element

Type Safety

List<int> ensures only integers can be added to the list

List Operations Explained

In Dart, lists are reference types. When you pass a list to a function and modify it, the changes affect the original list. Returning the list is optional but makes the function’s behavior more explicit and allows for method chaining.
Regular for loop:
Use when you need the index.For-in loop:
Use when you only need the values.
Add error handling to make the program more robust:

Enhanced Version

Here’s an enhanced version with additional features:

Practice Challenges

Challenge 1

Modify the program to also calculate and display the sum and average of all numbers entered.

Challenge 2

Add a function to find and display the maximum and minimum values in the list.

Challenge 3

Create a function to sort the list in ascending order before printing.

Challenge 4

Add a function to remove duplicate values from the list.