How to Implement Genetic Extension in Dart?

Extensions are a powerful tool that can help you write more expressive and robust code. One of the great things about extensions is that they can have generic type parameters. This means that you can write a single extension method that will work with multiple types. The type of list that the methods are called on determines how the type T is bound.

In the following example, we see how a few different types were extended to create new ones that fit specific needs – such as lists for operating on them or getters/setters for maintaining stateful information about an object’s properties!

extension MyCustomList<T> on List<T> {
  int get slotAvailable => 1000 - length;
  List<T> operator -() => reversed.toList();
  List<List<T>> halve() => [sublist(0, (length/2).round()), sublist((length/2).round())];
}
extension LogString<T> on T {
  String toLog(){
    return "LOG: ${toString()}";
  }
}

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close