Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extend a List in Dart?

Tags:

dart

I want to create a more specialized list in dart. I can't directly extend List. What are my options?

like image 562
Seth Ladd Avatar asked Apr 27 '13 00:04

Seth Ladd


People also ask

What is extension method in Dart?

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.

How do you add multiple values to a list in DART?

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.

How do you get the last element in a list in darts?

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.


1 Answers

To make a class implement List there are several ways :

  • Extending ListBase and implementing 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 } 
  • Mixin ListMixin and implementing 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 } 
  • Delegating to an other 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 } 
  • Delegating to an other 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).

like image 98
Alexandre Ardhuin Avatar answered Oct 09 '22 17:10

Alexandre Ardhuin