Dart Libraries #2
In this lesson, you will learn about directives in detail.
Introduction
In this lesson, you will learn about the following directives:
- The
part
directive - The
library
directive - The
export
directive
In addition to introducing the above directives, you will also learn to restrict the visibility of a library’s APIs.
Revisiting the setup
Let’s revisit the sample libraries lib1
and lib2
created in the previous lesson for demonstration.
Let’s create two libraries lib1
and lib2
for demonstration.
lib1
This library has APIs to calculate the sum and difference of two integers.
-
Addition API: The
int addition(int a, int b)
calculates the sum of two given integers and returns an integer. -
Subtraction API: The
int subtraction(int a, int b)
calculates the difference of two given integers and returns an integer. -
Internal Method-
int _add(int a, int b)
: It is an internal function/method that performs the real addition. This method is used by the addition API. Identifiers with the underscore (_) prefix are only available inside the library.
File ‘lib1.dart’:
int addition(int a, int b) => _add(a, b);
int subtraction(int a, int b) => a - b;
int _add(int a, int b) => a + b;
lib2
This library has APIs to check if the given number is even or odd.
- Even number API (
bool isNumberOdd(int num)
): This API takes a number and returns true if it is even or vice versa. - Odd number API (
bool isNumberOdd(int num)
): This API takes a number and returns true if it is odd or vice versa.
File ‘lib2.dart’:
bool isNumberOdd(int num) => num.isOdd;
bool isNumberEven(int num) => num.isEven;
//Added to demonstrate handle conflicting name in two different libraries
int addition(int a, int b) => a + b + 2;
Get hands-on with 1400+ tech skills courses.