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: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:Main Function
The main function coordinates the program flow:Complete Program
Key Concepts
List Declaration
List<int> numeros = [] creates an empty list of integersAdding Elements
Use
.add() method to append elements to a listFor-In Loop
for (var item in list) iterates through each elementType Safety
List<int> ensures only integers can be added to the listList Operations Explained
Why return the list if it's already modified?
Why return the list if it's already modified?
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.
What's the difference between for and for-in?
What's the difference between for and for-in?
Regular for loop:Use when you need the index.For-in loop:Use when you only need the values.
How to handle invalid input?
How to handle invalid input?
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.