Chapters

Hide chapters

Dart Apprentice: Beyond the Basics

First Edition · Flutter · Dart 2.18 · VS Code 1.71

Dart Apprentice: Beyond the Basics

Section 1: 15 chapters
Show chapters Hide chapters

7. Extension Methods
Written by Jonathan Sande

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

Up to this point in the book, you’ve been writing your own classes and methods. Often, though, you use other people’s classes when you’re programming. Those classes may be part of a core Dart library, or they may be from packages on Pub. In either case, you don’t have the ability to modify them at will.

However, Dart has a feature called extension methods that allows you to add functionality to existing classes. Even though they’re called extension methods, you can also add other members like getters, setters or even operators.

Extension Syntax

To make an extension, you use the following syntax:

extension on SomeClass {
  // your custom code
}

This should be located at the top level in a file, that is, not inside another class or function. Replace SomeClass with whatever class you want to add extra functionality to.

You may give the extension itself a name if you like. In that case, the syntax is as follows:

extension YourExtensionName on SomeClass {
  // your custom code
}

You can use whatever name you like in place of YourExtensionName. The name is only used to show or hide the extension when importing it in another library.

Have a look at a few of the following examples to see how extension methods work.

String Extension Example

Did you ever make secret codes when you were a kid, like a=1, b=2, c=3, and so on? For this example, you’re going to make an extension that will convert a string into a secret coded message. Then you’ll add another extension method to decode it.

Solving in the Normal Way

First, solve the problem as you would with a normal function. Add the following to your project:

String encode(String input) {
  final output = StringBuffer();
  for (final codePoint in input.runes) {
    output.writeCharCode(codePoint + 1);
  }
  return output.toString();
}
final original = 'abc';
final secret = encode(original);
print(secret);

Converting to an Extension

The next step is to convert the encode function above to an extension so that you can use it like so:

final secret = 'abc'.encoded;
extension on String {
  String get encoded {
    final output = StringBuffer();
    for (final codePoint in runes) {
      output.writeCharCode(codePoint + 1);
    }
    return output.toString();
  }
}
final secret = 'abc'.encoded;
print(secret);

Adding a Decode Extension

Add the decoded method inside the body of the String extension as well:

String get decoded {
  final output = StringBuffer();
  for (final codePoint in runes) {
    output.writeCharCode(codePoint - 1);
  }
  return output.toString();
}

Refactoring to Remove Code Duplication

Refactor your String extension by replacing the entire extension with the following:

extension on String {
  String get encoded => _code(1);
  String get decoded => _code(-1);

  String _code(int step) {
    final output = StringBuffer();
    for (final codePoint in runes) {
      output.writeCharCode(codePoint + step);
    }
    return output.toString();
  }
}

Testing the Results

To make sure that everything works, test both methods like so:

final original = 'I like extensions!';
final secret = original.encoded;
final revealed = secret.decoded;
print(secret);
print(revealed);
J!mjlf!fyufotjpot"
I like extensions!

Int Extension Example

Here’s an example of an extension on int.

extension on int {
  int get cubed {
    return this * this * this;
  }
}
print(5.cubed);
Uif!tfdsfu!up!mfbsojoh!Ebsu!xfmm!jt!up!dg"ewtkqwu"cpf"lwuv"vt{"vjkpiu0"Vlqfh#|rx*uh#uhdglqj#wklv/#wkdw#reylrxvo|#ghvfulehv#|rx1#Kssh$nsf%

Challenges

Before moving on, here’s a challenge to test your knowledge of extension methods. It’s best if you try to solve it yourself, but a solution is available with the supplementary materials for this book if you get stuck.

Challenge 1: Time to Code

Dart has a Duration class for expressing lengths of time. Make an extension on int so that you can express a duration like so:

final timeRemaining = 3.minutes;

Key Points

  • Extension methods allow you to give additional functionality to classes that are not your own.
  • Use extensions when they make sense, but try not to overuse them.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.

Unlock now