Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 10

Mobile Application Development

Duration: 65 min High School Grades: 9 - 12 CCSS, NGSS

Week 3

Iterable Collections
Tutorial: https://dart.dev/codelabs/iterables

Dr. Yasir Faheem


Associate Professor, NUST-SEECS
https://www.yasirfaheem.com/ 1
Disclaimer

These lecture slides have been prepared using the tutorials and content available on the
official Dart’s website (https://dart.dev/codelabs/iterables )

All the copyrights are reserved with the original content creators.

The purpose of these slides is to only teach the concepts of dart to students.

2
Recap

Asynchronous programming
 Future
 async
 await

3
Today’s Lecture

What are collections?

What is an Iterable?

• Learn:
• How to read elements of an Iterable.
• How to check if the elements of an Iterable satisfy a condition.
• How to filter the contents of an Iterable.
• How to map the contents of an Iterable to a different value.

4
Reading elements

You can read the elements of an iterable sequentially, using a for-in loop.

Behind the scenes, the for-in loop uses an iterator.

5
Reading Elements – first and last

Example: Using first and last


 To read the first and last elements of an iterable.

 Iterable class, you can’t access the elements directly, so you can’t call iterable[0] to access the
first element.

You can use first, which gets the first element.

6
Using firstWhere()

Use firstWhere() to find the first element that satisfies certain conditions.

Requires you to pass a predicate, which is a function that returns true if the input satisfies a
certain condition.

7
Using firstWhere()

In this example, you can see three


different ways to write a predicate:

As an expression: The test code has


one line that uses arrow syntax (=>).

As a block: The test code has multiple


lines between brackets and a return
statement.

As a function: The test code is in an


external function that’s passed to the
firstWhere() method as a parameter.
8
 If no element satisfies the test predicate and the orElse parameter isn’t provided, then
firstWhere() throws a StateError.

9
Checking conditions – any() and Every() methods

When working with Iterable, sometimes you need to verify that all the elements of a collection
satisfy some condition.

The Iterable class provides two methods that you can use to verify conditions:
 any(): Returns true if at least one element satisfies the condition.
 every(): Returns true if all elements satisfy the condition.

10

You might also like