10 Extension Methods examples in Dart: A Comprehensive Guide with Code Examples

In this article, we’ll delve into the world of Dart programming language and explore how to use extension methods effectively. We’ll present ten unique examples that demonstrate various applications of extension methods, from string manipulation to mat…


This content originally appeared on DEV Community and was authored by francesco agati

In this article, we'll delve into the world of Dart programming language and explore how to use extension methods effectively. We'll present ten unique examples that demonstrate various applications of extension methods, from string manipulation to mathematical operations on existing classes. Additionally, we'll provide a main function that tests these extensions to ensure their functionality.

10 Unique Extension Method Examples:

1 - String Extension - capitalizeFirstLetter(): Capitalizes the first letter of a given string.

extension CapString on String {
  String capitalizeFirstLetter() {
    return this[0].toUpperCase() + substring(1);
  }
}

Example usage:

void main() {
  String name = "john doe";
  print(name.capitalizeFirstLetter()); // Output: John Doe
}

2 - List Extension - findMaxElement(): Finds the maximum element in a list of integers.

extension MaxList on List<int> {
  int findMaxElement() {
    return reduce(max);
  }
}

Example usage:

void main() {
  List<int> numbers = [3, 9, 1, 7, 5];
  print(numbers.findMaxElement()); // Output: 9
}

3 - Int Extension - isEven(): Checks if an integer is even.

extension EvenInt on int {
  bool isEven() {
    return this % 2 == 0;
  }
}

Example usage:

void main() {
  int number = 15;
  print(number.isEven()); // Output: false
}

4 - List Extension - reverseList(): Reverses the elements of a list in-place.

extension RevList<T> on List<T> {
  void reverseList() {
    this.asMap().forEach((i, element) => this[i] = this[length - i - 1]);
  }
}

Example usage:

void main() {
  List<String> fruits = ["apple", "banana", "cherry"];
  fruits.reverseList();
  print(fruits); // Output: [cherry, banana, apple]
}

5 - String Extension - isPalindrome(): Checks if a string is a palindrome (reads the same backward as forward).

extension PalinString on String {
  bool isPalindrome() {
    return this == reverse;
  }
}

Example usage:

void main() {
  String word = "radar";
  print(word.isPalindrome()); // Output: true
}

6 - List Extension - average(): Calculates the average of a list of numbers.

extension AvgList on List<num> {
  double average() {
    return reduce((sum, element) => sum + element) / length;
  }
}

Example usage:

void main() {
  List<double> scores = [90.5, 87.3, 92.1, 88.9];
  print(scores.average()); // Output: 89.175
}

7 - Int Extension - factorial(): Calculates the factorial of an integer.

extension FactInt on int {
  int factorial() {
    return (this < 2) ? 1 : this * (this - 1).factorial();
  }
}

Example usage:

void main() {
  int number = 5;
  print(number.factorial()); // Output: 120
}

8 - List Extension - removeDuplicates(): Removes duplicate elements from a list.

extension UniqList<T> on List<T> {
  void removeDuplicates() {
    this.replaceRange(0, length, toSet().toList());
  }
}

Example usage:

void main() {
  List<int> numbers = [1, 2, 3, 4, 4, 5, 6, 6, 7];
  numbers.removeDuplicates();
  print(numbers); // Output: [1, 2, 3, 4, 5, 6, 7]
}

9 - String Extension - countVowels(): Counts the number of vowels in a string.

extension VowelString on String {
  int countVowels() {
    return replaceAll(RegExp(r'[^aeiou]'), '').length;
  }
}

Example usage:

void main() {
  String sentence = "The quick brown fox jumps over the lazy dog";
  print(sentence.countVowels()); // Output: 5
}

10 - List Extension - isSorted(): Checks if a list of integers is sorted in ascending order.

extension SortList on List<int> {
  bool isSorted() {
    return this == toList()..sort();
  }
}

Example usage:

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  print(numbers.isSorted()); // Output: true
}

Extension methods in Dart provide a powerful way to add functionality to existing classes without modifying their source code. By using these extensions, you can write cleaner and more maintainable code that is easier to understand and use. In this article, we've presented ten unique examples of extension methods for various data types and demonstrated how they can be used effectively.


This content originally appeared on DEV Community and was authored by francesco agati


Print Share Comment Cite Upload Translate Updates
APA

francesco agati | Sciencx (2024-06-22T20:10:34+00:00) 10 Extension Methods examples in Dart: A Comprehensive Guide with Code Examples. Retrieved from https://www.scien.cx/2024/06/22/10-extension-methods-examples-in-dart-a-comprehensive-guide-with-code-examples/

MLA
" » 10 Extension Methods examples in Dart: A Comprehensive Guide with Code Examples." francesco agati | Sciencx - Saturday June 22, 2024, https://www.scien.cx/2024/06/22/10-extension-methods-examples-in-dart-a-comprehensive-guide-with-code-examples/
HARVARD
francesco agati | Sciencx Saturday June 22, 2024 » 10 Extension Methods examples in Dart: A Comprehensive Guide with Code Examples., viewed ,<https://www.scien.cx/2024/06/22/10-extension-methods-examples-in-dart-a-comprehensive-guide-with-code-examples/>
VANCOUVER
francesco agati | Sciencx - » 10 Extension Methods examples in Dart: A Comprehensive Guide with Code Examples. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/22/10-extension-methods-examples-in-dart-a-comprehensive-guide-with-code-examples/
CHICAGO
" » 10 Extension Methods examples in Dart: A Comprehensive Guide with Code Examples." francesco agati | Sciencx - Accessed . https://www.scien.cx/2024/06/22/10-extension-methods-examples-in-dart-a-comprehensive-guide-with-code-examples/
IEEE
" » 10 Extension Methods examples in Dart: A Comprehensive Guide with Code Examples." francesco agati | Sciencx [Online]. Available: https://www.scien.cx/2024/06/22/10-extension-methods-examples-in-dart-a-comprehensive-guide-with-code-examples/. [Accessed: ]
rf:citation
» 10 Extension Methods examples in Dart: A Comprehensive Guide with Code Examples | francesco agati | Sciencx | https://www.scien.cx/2024/06/22/10-extension-methods-examples-in-dart-a-comprehensive-guide-with-code-examples/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.