Extensions: Handling Conflicts
Learn to handle conflicts in similar named extensions.
What Is a Conflict?
Imagine that you have a library/file to hold all common extensions of a project. Let’s say this file is called ‘extensions_lib.dart’.
The ‘extensions_lib’ has two extensions:
- An extension on
List
type namedMyList
. - An extension on
double
type namedMyDouble
.
MyList
Extension
The MyList
extension defines a method firstItem()
that returns the first element of the list. The return type is generic which is also represented as T
. You will learn more about generics later in the course.
extension MyList<T> on List<T> {
//Returns the first item in this list
T first() => this[0];
}
MyDouble
extension
The MyDouble
extension defines a method tenTimes()
that returns ten times the double value it’s called on.
extension MyDouble on double {
double tenTimes() => this * 10;
}
The ‘extensions_lib.dart’ File
Here are the contents of ‘extensions_lib.dart’:
extension MyList<T> on List<T> {
//Returns the first item in this list
T firstItem() => this[0];
}
extension MyDouble on double {
double tenTimes() => this * 10;
}
main.dart
The main.dart
uses the extension methods to print the first item in a given list and also prints ten times the given double value.
The MyList
extension’s firstItem()
method is used to print the first item on the list.
The MyDouble
extension’s tenTimes()
method is used to print ten times the value of the given double.
To utilize the extensions defined in the file, you must import the ‘extensions_lib.dart’ file.
//importing extension methods
import 'extensions_lib.dart';
void main() {
List<String> names = ["Priyanka", "Tyagi"];
//print first name using extension
print(names.firstItem());
//Print MyDouble extension method `tenTimes()`
print(10.0.tenTimes());
}
Output:
Priyanka
100.0
So far, so good. Let’s assume the main.dart
file has another similar extension method firstItem()
defined locally. See example below.
extension<T> on List<T> {
//Returns the first item in this list
T firstItem() => this[0];
}
A local extension is not required to be named.
Now, the following line in main.dart
will throw a compile-time error since it is confused about which firstItem()
to use.
print(names.firstItem());
Try It Yourself
Run the code below to see the error caused by the conflicting extensions.
main.dart:14:15: Error: The method 'firstItem' isn't defined for the class 'List<String>'.
- 'List' is from 'dart:core'.
Try correcting the name to the name of an existing method, or defining a method named 'firstItem'.
print(names.firstItem());
^^^^^^^^^
Get hands-on with 1400+ tech skills courses.