Dart's Unnamed Extensions: A Basic Usage Guide
Kenji Tomita
Posted on February 11, 2024
Dart is designed to make coding more efficient by providing a variety of useful features. Among these, unnamed extensions are particularly handy when you want to provide extension functionality within a specific scope only. This article will explain the basic usage of unnamed extensions in Dart.
What are Unnamed Extensions?
Unnamed extensions are a syntax in Dart that allows you to define an extension without explicitly naming it. These extensions are only visible within the library (file) they are defined in and cannot be accessed from outside their scope. This allows for the safe addition of custom functionality that only makes sense within a specific file or module while avoiding API conflicts.
Example of Unnamed Extension
Here is a simple example of an unnamed extension that provides a default value for int?
types.
// extension.dart
extension on int? {
int get orDefault {
return this ?? 10;
}
}
This extension adds an orDefault
getter to the int?
type, providing a default value of 10
if the variable is null
.
Example of Calling the Extension
Attempting to use the above extension from a different file would look like this:
// main.dart
import 'extension.dart';
void main() {
int? myValue;
// Compile error: The getter 'orDefault' isn't defined for the type 'int'.
print(myValue.orDefault);
}
This code results in a compile error because the unnamed extension defined in extension.dart
is not visible from main.dart
. This demonstrates that unnamed extensions are only available within the library they are defined in.
Reference Link
The Dart official documentation provides more detailed information about unnamed extensions. For further details, please refer to the following link:
Conclusion
Unnamed extensions are a powerful feature in Dart for making code writing more efficient and safe. By appropriately using this feature to add custom functionality needed only within a specific scope, you can build a cleaner and more maintainable codebase.
Posted on February 11, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.