Dart| Flutter How to: get First and Last Element from a List with Example
This tutorial shows how to get the first and last element from a Dart or Flutter List
dart programming provides multiple ways to retrieve the first and last element from a list.
How to get the First element in dart/flutter?
dart list provides multiple ways to retrieve the first element.
List.first
property- Returns the first element from a given list, if the list is not empty.
- if the list is empty, It throws an error Uncaught Error: Bad state: No element
import 'dart:async';
void main() async {
List list = [];
print(list);//[]
print(list.first); // Uncaught Error: Bad state: No element
}
- List index with zero
- List elements are inserted with insertion order and elements are indexed with
0
to end element withlist.length - 1
. - index=0 is the first element. Elements get using
List[index]
syntax. - If the list is empty, It throws an error Uncaught Error: RangeError (index): Index out of range: no indices are valid: 0
- List elements are inserted with insertion order and elements are indexed with
import 'dart:async';
void main() async {
List list = [];
print(list);//[]
print(list[0]); // Uncaught Error: RangeError (index): Index out of range: no indices are valid: 0
}
Here is a Complete code to get the first element from a given list.
import 'dart:async';
void main() async {
List list = [5, 7, 33, 9];
print(list);
print(list.first); // 5
print(list[0]); // 5
}
How to get the last element from a list in dart and flutter?
dart list provides multiple ways to retrieve the last element.
- List. last property
- The last element is returned from a given list if the list is not empty.
- if the list is empty, It throws an error Uncaught Error: Bad state: No element
import 'dart:async';
void main() async {
List list = [];
print(list);//[]
print(list.last); // Uncaught Error: Bad state: No element
}
- List index with the list.length -1
- List elements are inserted with insertion order and elements are indexed with
0
to end element withlist.length - 1
. list.length - 1
is the last element. Elements get usingList[index]
syntax.- If list is empty, calling
List[list.length - 1]
throws an error Uncaught Error: RangeError (index): Index out of range: index must not be negative: -1
- List elements are inserted with insertion order and elements are indexed with
import 'dart:async';
void main() async {
List list = [];
print(list);//[]
print(list[0]); // // Uncaught Error: RangeError (index): Index out of range: index must not be negative: -1
}
First, You have a list
is created with initializing syntax.
Here is an example
import 'dart:async';
void main() async {
List list = [5, 7, 33, 9];
print(list);
print(list.last); // 9
print(list[list.length-1]); // 0
}
Conclusion
To summarize, We can easily get the Last and first elements of a list using first and last and list index syntax.