THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
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.
dart list provides multiple ways to retrieve the first element.
List.first
propertyimport 'dart:async';
void main() async {
List list = [];
print(list);//[]
print(list.first); // Uncaught Error: Bad state: No element
}
0
to end element with list.length - 1
.List[index]
syntax.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
}
dart list provides multiple ways to retrieve the last element.
import 'dart:async';
void main() async {
List list = [];
print(list);//[]
print(list.last); // Uncaught Error: Bad state: No element
}
0
to end element with list.length - 1
.list.length - 1
is the last element. Elements get using List[index]
syntax.List[list.length - 1]
throws an error Uncaught Error: RangeError (index): Index out of range: index must not be negative: -1import '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
}
To summarize, We can easily get the Last and first elements of a list using first and last and list index syntax.
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts