LinkedList stores data elements in format of Nodes. In flutter we can make dynamic LinkedList by extends LinkedListEntry class. In today's tutorial we will create a dynamic LinkedList and perform various operations.
Flutter Dart LinkedList Example
1. Import dart:collection class in your main.dart file.
import 'dart:collection';
2. Creating a class TestLinkedList extends LinkedListEntry. This is our LinkedList separate class. It has two variables ID and Name.
final class TestLinkedList extends LinkedListEntry<TestLinkedList> {
final int id;
final String name;
TestLinkedList(this.id, this.name);
@override
String toString() {
return '$id : $name';
}
}
3. Creating Object of TestLinkedList in our main() class.
final linkedListOBJ = LinkedList<TestLinkedList>();
4. Adding multiple items in linked list with addAll() method.
linkedListOBJ.addAll(
[TestLinkedList(1, 'A'), TestLinkedList(2, 'B'), TestLinkedList(3, 'C')]);
5. Get first Item of LinkedList in dart.
print(linkedListOBJ.first);
6. Get Last item of LinkedList in dart.
print(linkedListOBJ.last)
7. Adding new item in LinkedList after first item.
linkedListOBJ.first.insertAfter(TestLinkedList(15, 'E'));
8. Adding new item in LinkedList before first item.
linkedListOBJ.last.insertBefore(TestLinkedList(10, 'D'));
9. Printing all LinkedList items on screen using For loop.
for (var entry in linkedListOBJ) {
print(entry);
}
10. Get length of LinkedList.
print(linkedListOBJ.length);
11. Checking LinkedList is Empty or Not.
print(linkedListOBJ.isEmpty);
12. Removing first item form LinkedList.
linkedListOBJ.first.unlink();
13. Removing last item from LinkedList.
linkedListOBJ.remove(linkedListOBJ.last);
14. Removing item with Index number from LinkedList.
linkedListOBJ.elementAt(2).unlink();
15. Remove all items from LinkedList.
linkedListOBJ.clear();
Source code of main.dart file:
import 'dart:collection';
final class TestLinkedList extends LinkedListEntry<TestLinkedList> {
final int id;
final String name;
TestLinkedList(this.id, this.name);
@override
String toString() {
return '$id : $name';
}
}
void main() {
final linkedListOBJ = LinkedList<TestLinkedList>();
linkedListOBJ.addAll(
[TestLinkedList(1, 'A'), TestLinkedList(2, 'B'), TestLinkedList(3, 'C')]);
print(linkedListOBJ.first);
print(linkedListOBJ.last);
linkedListOBJ.first.insertAfter(TestLinkedList(15, 'E'));
linkedListOBJ.last.insertBefore(TestLinkedList(10, 'D'));
for (var entry in linkedListOBJ) {
print(entry);
}
print(linkedListOBJ.length);
print(linkedListOBJ.isEmpty);
linkedListOBJ.first.unlink();
print(linkedListOBJ);
linkedListOBJ.remove(linkedListOBJ.last);
print(linkedListOBJ);
linkedListOBJ.elementAt(2).unlink();
print(linkedListOBJ);
linkedListOBJ.clear();
print(linkedListOBJ);
}
Output:
Comments
Post a Comment