I want to create a more specialized list in dart. I can't directly extend List. What are my options?
Extension methods, introduced in Dart 2.7, are a way to add functionality to existing libraries. You might use extension methods without even knowing it. For example, when you use code completion in an IDE, it suggests extension methods alongside regular methods.
You can use . add() method to add single item to a list and . addAll() method to add multiple items to a list in Dart programming language.
you can use last property for read/write, inherited-getter: last is a returns the last element from the given list. The best one is lst[lst. length-1] way because in the "last" property ,it loops through the list until the last element is got , so it will be slower way.
To make a class implement List there are several ways :
length
, operator[]
, operator[]=
and length=
:import 'dart:collection'; class MyCustomList<E> extends ListBase<E> { final List<E> l = []; MyCustomList(); void set length(int newLength) { l.length = newLength; } int get length => l.length; E operator [](int index) => l[index]; void operator []=(int index, E value) { l[index] = value; } // your custom methods }
length
, operator[]
, operator[]=
and length=
:import 'dart:collection'; class MyCustomList<E> extends Base with ListMixin<E> { final List<E> l = []; MyCustomList(); void set length(int newLength) { l.length = newLength; } int get length => l.length; E operator [](int index) => l[index]; void operator []=(int index, E value) { l[index] = value; } // your custom methods }
List
with DelegatingList
from the quiver package:import 'package:quiver/collection.dart'; class MyCustomList<E> extends DelegatingList<E> { final List<E> _l = []; List<E> get delegate => _l; // your custom methods }
List
with DelegatingList
from the collection package:import 'package:collection/wrappers.dart'; class MyCustomList<E> extends DelegatingList<E> { final List<E> _l; MyCustomList() : this._(<E>[]); MyCustomList._(l) : _l = l, super(l); // your custom methods }
Depending on your code each of those options has their advantages. If you wrap/delegate an existing list you should use the last option. Otherwise, use one of the two first options depending on your type hierarchy (mixin allowing to extend another Object).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With