Dart Libraries

 

Dart Libraries

In Dart, the library is the collection of the routine or set of programming instructions. Dart consists of many sets of built-in libraries that are beneficial to hold routines (functions, set of classes, etc.), and regularly used. A Dart library contains constants, functions, properties, exceptions, and typedefs, and set of classes.

Importing a library

To work with the library, we must import it into the current program. The Dart provides the import keyword, which is used to make the library available in the current file. We can use multiple libraries in a single file.

For example - Dart built-in library URIs is used as dart scheme to refer to a library. Other libraries can use a file system path or the package: scheme to specify its URIs. The package manager pub in Dart provides the libraries and uses the package scheme.

We are describing some commonly used libraries below.

Sr.LibraryDescription
1.dart:ioThis library consists of File, HTTP, socket, and other I/O support for server applications. This library is not suitable for browser-based applications. We don't need to import explicitly because it is imported by default.
2.Dart:coreThis library consists of Collection, built-in types, and other core functionality for each dart program. It is imported by default.
3.Dart: mathThis library consists of the rich mathematical functions, constant, and random number generator.
4.Dart: convertIt is used to Encoders and decoders for converting the different data representations such as JSON and UTF
5.Dart: typed_dataIt represents the lists that store the fixed-sized data efficiently (for example - unsigned 8-byte integer).

Let's understand the following example of importing and using a library function.

Example - Importing and using a Library

  1. import 'dart:math';   // Importing built-in library  
  2. void main() {   
  3.    print("Square root of 36 is: ${sqrt(36)}");   
  4. }  

Output:

Square root of 25 is: 5.0

Explanation:

In the above code, we imported the built-in library 'dart:math'. It provides the many built-in mathematical function, here we used the sqrt() function with number. It takes a number as an argument that we want to find its square root of. We passed an integer number 25 in sqrt() function, and it retuned an output as 5.

Encapsulation in Libraries

Dart provides the facility to encapsulate or restrict access the content of the dart library. It can be done by using the _(underscore), followed by the identifier. The _(underscore) symbol makes the library's content completely private. The syntax is given below.

Syntax:

  1. _identifier  

Example -

We define a library called Greetings that has a private function.

  1. library Greetings;        
  2. // We define a function using the _underscore as a prefix.                        
  3. void _sayHi(msg) {  
  4.    print("We will access this method in another program:${msg}");        
  5. }  

The above file saves as greetings.dart, now we import the library.

  1. import 'greetings.dart' as w;   
  2. void main() {   
  3.    w._sayHi("Hello Javatpoint");   
  4. }  

Output:

After running the above code, it throws an error because we have declared the library with the private method and try to access it in other file.

Unhandled exception: 
No top-level method 'w._sayHi' declared.  
NoSuchMethodError: method not found: 'w._sayHi' 
Receiver: top-level 
Arguments: [...] 
#0 NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:184) 
#1 main (file:///C:/Users/Administrator/WebstormProjects/untitled/Assertion.dart:6:3) 
#2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) 
#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)

Creating Custom Libraries (User-defined Library)

We can also use our own code as a library and import it when needed. This type of library is called a custom library. Below are the steps to create a custom library.

Step - 1: Declaring a Library

The library statement is used to create a library explicitly. The syntax is given below.

Syntax:

  1. library library_name    
  2. // library contents go here   

Step - 2: Connecting a Library

We can connect a library in two ways.

  • Within the same directory
  1. import 'library_name'  
  • From a different directory
  1. import 'dir/library_name'  

Let's understand the following example -

Example - Custom Library

  1. library calculator_simple;    
  2. import 'dart:math';   
  3.   
  4. //library content  
  5. int add(int num1,int num2){   
  6.    print("inside add method of calculator_simple Library ") ;   
  7.    return num1+num2;   
  8. }    
  9. int multiplication(int num1,int num2){   
  10.    print("inside multiplication method of calculator_simple Library ") ;   
  11.    return num1*num2;   
  12. }    
  13.   
  14. int subtraction(int num1,int num2){   
  15.    print("inside subtraction  method of calculator_simple Library ") ;   
  16.    return num1-num2;   
  17. }    
  18.   
  19. int modulus(int num1,int num2){   
  20.    print("inside modulus  method of calculator_simple Library ") ;   
  21.    return num1%num2;   
  22. }    

Now we import the above custom file in current file called 'library.dart'.

  1. import 'calculator.dart';    
  2. void main() {  
  3.    var n1 = 30;   
  4.    var n2 = 10;   
  5.    var sum = add(n1,n2);   
  6.    var mod = modulus(n1,n2);   
  7.    var mul = multiplication(n1,n2);  
  8.    var div = divide(n1,n2);  
  9.    var sub = subtraction(n1,n2);  
  10.      
  11.      
  12.    print("$n1 + $n2 = $sum");   
  13.    print("$n1 %  $n2= $mod");   
  14.    print("$n1 + $n2 = $mul");   
  15.    print("$n1 - $n2 = $sub");  
  16.      
  17. }  

Output:

inside add method of calculator_simple Library
inside modulus  method of calculator_simple Library
inside multiplication method of calculator_simple Library
inside subtraction  method of calculator_simple Library
30 + 10 = 40
30 %  10= 0
30 + 10 = 300
30 - 10 = 20

Copy the above code and paste it into your dart editor and observe the result.

Note - The custom library must be imported by its saved file name such as we imported it in the current working file with the calculator_simple name.

Name Alias of Library

Dart allows us to import multiple libraries into the current working file, but if we create the same function name within the different libraries, it will create conflict while accessing these functions. The Dart compiler might be confused to identify the particular function in different library. To overcome this scenario, Dart provides the as keyword for specifying the prefix. The syntax is given below.

Syntax:

  1. import 'library_uri' as prefix  

Let's understand the following example -

Example -

First, we define a library: greeting.dart

  1. library greetings;    
  2. void sayHi(msg){   
  3.    print("Learn the Dart with ${msg}");  
  4. }  

Next, we define the new library: hellogreetings.dart

  1. library hellogreetings;   
  2. void sayHi(msg){   
  3.    print("${msg} provides the tutorial on all technical retated topic");   
  4. }  

Now, we import the above libraries with the as prefix.

  1. import 'greetings.dart';   
  2. import 'hellogreetings.dart' as gret;    
  3.   
  4. // using as prefix avoids function name clashes   
  5. void main(){   
  6.    sayHi("JavaTpoint");   
  7.    gret.sayHi("JavaTpoint");   // To eliminate the name confliction  
  8. }  

Output:

Learn the Dart with JavaTpoint
JavaTpoint provides the tutorial on all technical related topic

Comments