Skip to main content

Command Palette

Search for a command to run...

Dart Number: Int Extension

Published
2 min readView as Markdown
Dart Number: Int Extension
P

I'm Computer Engineering Student. Learning Status DSA in Java, Dart Development, Python in Django Development. Best part is Communication Skills, Marketing, Accounting.

Here's how you can create an extension for the int class in Dart:

Structure:

Dart

extension {ExtensionName} on int {
  // Methods, getters, setters, or operators applicable to integers
}

Explanation:

  • extension {ExtensionName}: Define the extension with an optional name.

  • on int: Specify that this extension applies to the int class.

  • // Methods, getters, setters, or operators: This section contains functionalities specifically designed to work with integers.

Example - Even or Odd check:

Dart

extension IntExtension on int {
  bool isEven() {
    return this % 2 == 0;
  }
}
  • This extension defines a method named isEven() that checks if the current integer (this) is even by using the modulo operator (%).

Usage:

Dart

int number = 10;
if (number.isEven()) {
  print("Even number");
} else {
  print("Odd number");
}

Additional functionalities:

  • You can extend the int class with various methods for integer manipulation:

    • Check for divisibility (isDivisibleBy(int divisor))

    • Absolute value (abs())

    • Custom logic for specific integer operations

Points to Consider:

  • Naming: Choose descriptive names for extension methods to improve code clarity (e.g., isPositive(), isPrime()).

  • Overuse: Avoid creating too many extension methods for int as it might clutter the codebase.

Resources:

Further Exploration:

  • Explore existing libraries like intx (https://pub.dev/packages/intl4x) that provide pre-defined extensions for the int class.

  • Consider creating custom extensions only when the required functionality is not readily available or to enhance code readability for specific use cases.

By effectively using extensions, you can add custom functionalities to the int class in Dart, making your code more concise and expressive.

More from this blog

Parth Chauhan's blog

87 posts

Learner, Accountant, Marketer, Programmer.