I want to add my own methods to a few Dart Classes

2019-05-21 01:01发布

问题:

My attempt to simply 'Extend' the Map class fails because List is an interface and cannot be extended but must be implemented.

The goal was simply to add a few methods on top of some existing class such as:

List.add_unique(item) where I only want to append if the item does not already exist. This can be done nicely by and-ing the append !=null logic with List.indexOf(item) != -1 (where -1 is notFound). This would be a good and easy to understand example?

But, how to accomplish this in the shortest, least overall overhead sort of way? I think I would be OK with loose typing - at least to start with.

There are other methods I wish to add and or modify such as an .add() method for the Map class.

I have not dealt with interfaces for many years and I'm thinking there might just be a much easier way overall to get started on this side of my project.

Thanks!

回答1:

I've hit this problem too. The best workaround at the moment is to create a class that forwards all of the method calls. Something like: https://github.com/dart-lang/html5lib/blob/master/lib/src/list_proxy.dart

Then you can inherit from ListProxy and override or add whatever methods you need.

If people find this useful enough, maybe we can put it in its own pub package. I'm hoping we can get dart:core fixed, though, so it supports inheritance from all of the core collection classes.

By the way, if you're trying to override a method in Map it's much easier: you can import 'dart:coreimpl'; and extend HashMapImplementation.