The Extension
methods is to add functionality to a class without changing the class or creating a subclass.
When you’re using someone else API or when you implement a library that’s widely used, it’s often impractical or impossible to change the API. But you might still want to add some functionality.
Use the following syntax to create an extension:
extension <extension name> on <type> {
(<member definition>)*
}
For example, here’s how you might implement an extension on the String class:
create a file string_apis.dart
, and implement following code.
extension NumberParsing on String {
int parseInt() {
return int.parse(this);
}
double parseDouble() {
return double.parse(this);
}
}
This code snippet shows how use extension method
// Import a library that contains an extension on String.
import 'string_apis.dart';
void main() {
print('42'.parseInt()); // Use an extension method.
}