Dart Programming – Libraries

  • Post author:
  • Post category:Dart
  • Post comments:1 Comment
Dart Programming libraries

In this guide, we will discuss Libraries in Dart Programming Language. A library in a programming language represents a collection of routines (set of programming instructions). Dart has a set of built-in libraries that are useful to store routines that are frequently used. A Dart library comprises of a set of classes, constants, functions, typedefs, properties, and exceptions.

Importing a library

Importing makes the components in a library available to the caller code. The import keyword is used to achieve the same. A dart file can have multiple import statements.

Built in Dart library URIs use the dart: scheme to refer to a library. Other libraries can use a file system path or the package: scheme to specify its URI. Libraries provided by a package manager such as the pub tool uses the package: scheme.

The syntax for importing a library in Dart is given below −

import 'URI'

Consider the following code snippet −

import 'dart:io' 
import 'package:lib1/libfile.dart' 

If you want to use only part of a library, you can selectively import the library. The syntax for the same is given below −

import 'package: lib1/lib1.dart' show foo, bar;  
// Import only foo and bar. 

import 'package: mylib/mylib.dart' hide foo;  
// Import all names except foo

Some commonly used libraries are given below −

Sr.NoLibrary & Description
1dart:ioFile, socket, HTTP, and other I/O support for server applications. This library does not work in browser-based applications. This library is imported by default.
2dart:coreBuilt-in types, collections, and other core functionality for every Dart program. This library is automatically imported.
3dart: mathMathematical constants and functions, plus a random number generator.
4dart: convert
Encoders and decoders for converting between different data representations, including JSON and UTF-8.
5dart: typed_data
Lists that efficiently handle fixed sized data (for example, unsigned 8 byte integers).

Example : Importing and using a Library

The following example imports the built-in library dart: math. The snippet calls the sqrt() function from the math library. This function returns the square root of a number passed to it.

import 'dart:math'; 
void main() { 
   print("Square root of 36 is: ${sqrt(36)}"); 
}

Output

Square root of 36 is: 6.0

Encapsulation in Libraries

Dart scripts can prefix identifiers with an underscore ( _ ) to mark its components private. Simply put, Dart libraries can restrict access to its content by external scripts. This is termed as encapsulation. The syntax for the same is given below −

Syntax

_identifier

Example

At first, define a library with a private function.

library loggerlib;                            
void _log(msg) {
   print("Log method called in loggerlib msg:$msg");      
} 

Next, import the library

import 'test.dart' as web; 
void main() { 
   web._log("hello from webloggerlib"); 
} 

The above code will result in an error.

Unhandled exception: 
No top-level method 'web._log' declared.  
NoSuchMethodError: method not found: 'web._log' 
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

Dart also allows you to use your own code as a library. Creating a custom library involves the following steps −

Step 1: Declaring a Library

To explicitly declare a library, use the library statement. The syntax for declaring a library is as given below −

library library_name  
// library contents go here 

Step 2: Associating a Library

You can associate a library in two ways −

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

Example: Custom Library

First, let us define a custom library, calculator.dart.

library calculator_lib;  
import 'dart:math'; 

//import statement after the libaray statement  
int add(int firstNumber,int secondNumber){ 
   print("inside add method of Calculator Library ") ; 
   return firstNumber+secondNumber; 
}  
int modulus(int firstNumber,int secondNumber){ 
   print("inside modulus method of Calculator Library ") ; 
   return firstNumber%secondNumber; 
}  
int random(int no){ 
   return new Random().nextInt(no); 
}

Next, we will import the library −

import 'calculator.dart';  
void main() {
   var num1 = 10; 
   var num2 = 20; 
   var sum = add(num1,num2); 
   var mod = modulus(num1,num2); 
   var r = random(10);  
   
   print("$num1 + $num2 = $sum"); 
   print("$num1 % $num2= $mod"); 
   print("random no $r"); 
} 

The program should produce the following output −

inside add method of Calculator Library  
inside modulus method of Calculator Library  
10 + 20 = 30 
10 % 20= 10 
random no 0 

Library Prefix

If you import two libraries with conflicting identifiers, then you can specify a prefix for one or both libraries. Use the ‘as’ keyword for specifying the prefix. The syntax for the same is given below −

Syntax

import 'library_uri' as prefix

Example

First, let us define a library: loggerlib.dart.

library loggerlib;  
void log(msg){ 
   print("Log method called in loggerlib msg:$msg");
}   

Next, we will define another library: webloggerlib.dart.

library webloggerlib; 
void log(msg){ 
   print("Log method called in webloggerlib msg:$msg"); 
} 

Finally, we will import the library with a prefix.

import 'loggerlib.dart'; 
import 'webloggerlib.dart' as web;  

// prefix avoids function name clashes 
void main(){ 
   log("hello from loggerlib"); 
   web.log("hello from webloggerlib"); 
} 

It will produce the following output −

Log method called in loggerlib msg:hello from loggerlib 
Log method called in webloggerlib msg:hello from webloggerlib 

Next Topic : Click Here

This Post Has One Comment

Leave a Reply