Dart Libraries #1
In this lesson, you will be introduced to the Dart libraries.
Introduction
This lesson is an introduction to libraries in Dart/Flutter. A library is a reusable module for frequently used programs/code. It helps to write a modular codebase. In Dart, each app is a library.
The lesson about libraries is divided into two lessons.
Dart Libraries #1: The first lesson covers how to use Dart libraries including the following:
- Using Prefix for library
- Importing specific APIs
- Defer/delay loading library
Dart Libraries #2: The second lesson instructs on understanding the following directives:
- The
part
directive - The
library
directive - The
export
directive
Setup
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 numbers are 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.