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

import 'dart:math';   // Importing built-in library  

void main() {   

   print("Square root of 36 is: ${sqrt(36)}");   

} 

    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:

    _identifier  

    Example –

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

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

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

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

      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:

      library library_name    
      
      // library contents go here   

        Step – 2: Connecting a Library

        We can connect a library in two ways.

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

        Let’s understand the following example –

        Example – Custom Library

        library calculator_simple;    
        
        import 'dart:math';   
        
          
        
        //library content  
        
        int add(int num1,int num2){   
        
           print("inside add method of calculator_simple Library ") ;   
        
           return num1+num2;   
        
        }    
        
        int multiplication(int num1,int num2){   
        
           print("inside multiplication method of calculator_simple Library ") ;   
        
           return num1*num2;   
        
        }    
        
          
        
        int subtraction(int num1,int num2){   
        
           print("inside subtraction  method of calculator_simple Library ") ;   
        
           return num1-num2;   
        
        }    
        
          
        
        int modulus(int num1,int num2){   
        
           print("inside modulus  method of calculator_simple Library ") ;   
        
           return num1%num2;   
        
        }    

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

          import 'calculator.dart';    
          
          void main() {  
          
             var n1 = 30;   
          
             var n2 = 10;   
          
             var sum = add(n1,n2);   
          
             var mod = modulus(n1,n2);   
          
             var mul = multiplication(n1,n2);  
          
             var div = divide(n1,n2);  
          
             var sub = subtraction(n1,n2);  
          
               
          
               
          
             print("$n1 + $n2 = $sum");   
          
             print("$n1 %  $n2= $mod");   
          
             print("$n1 + $n2 = $mul");   
          
             print("$n1 - $n2 = $sub");  
          
               
          
          } 

            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:

            import 'library_uri' as prefix  

            Let’s understand the following example –

            Example –

            First, we define a library: greeting.dart

            library greetings;    
            
            void sayHi(msg){   
            
               print("Learn the Dart with ${msg}");  
            
            }

            Next, we define the new library: hellogreetings.dart

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

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

              import 'greetings.dart';   
              
              import 'hellogreetings.dart' as gret;    
              
                
              
              // using as prefix avoids function name clashes   
              
              void main(){   
              
                 sayHi("JavaTpoint");   
              
                 gret.sayHi("JavaTpoint");   // To eliminate the name confliction  
              
              }

              Output:

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

              Comments

              Leave a Reply

              Your email address will not be published. Required fields are marked *