Dart show Keyword :Avoid Importing Unnecessary Library functions
In Dart, the show keyword proves highly useful when working with large imports. You can avoid unnecessary functions in your program by specifying the required functions from the library during import. The show keyword in Dart is essential when you want to use only specific functions from a library.
Why should we use the ‘show’ keyword in Dart?
When you import a library in Dart, you might not necessarily need or want to bring in all of its components. The show keyword allows you to specify exactly which parts of the library you want to make available in your code.
Consider the following example:
import 'dart:math' show min, max;
void main() {
print(min(5, 20));
print(max(5, 20));
}
Here, ‘show min, max’ means that you can only access the min() and max() functions from the dart:math library.
5
20
Let’s add another function for testing:
var number = 25;
var squareRoot = sqrt(number);
Update the code:
import 'dart:math' show min, max;
void main() {
print(min(5, 20));
print(max(5, 20));
var number = 25;
var squareRoot = sqrt(number);
}
The above program will generate an error like the one below:
The function ‘sqrt’ isn’t defined. Try importing the library that defines ‘sqrt’, correcting the name to the name of an existing function, or defining a function named ‘sqrt’.
The main reason for causing this error is importing only specific functions from the dart:math library. How can we fix this?
import 'dart:math' show min, max, sqrt;
Fix :
Open the dart pad and write the following code:
import 'dart:math' show min, max, sqrt;
void main() {
print(min(5, 20));
print(max(5, 20));
var number = 25;
var squareRoot = sqrt(number);
print(squareRoot);
}
5
20
5
Overview
The show keyword in Dart offers a targeted approach when importing libraries, allowing developers to selectively bring in only specific functions, classes, or variables from a library. This helps reduce clutter in the codebase by excluding unnecessary elements, resulting in improved readability and more efficient memory usage.
Additionally, it optimizes application performance by excluding unused elements, resulting in smaller file sizes and more efficient resource allocation during runtime. Overall, the show keyword empowers developers to manage dependencies more precisely, fostering cleaner, more efficient codebases.
Advantages of using ‘show’ keyword :
Selective Import
Allows developers to import specific functions, classes, or variables from a library.
Maintenance
Facilitates easier maintenance by clearly indicating the imported elements.
Optimized Performance
Reduces unnecessary imports, resulting in smaller file sizes and more efficient memory usage.
Resource Allocation
Streamlines resource allocation during runtime by excluding unused elements.
Happy Coding!