English 中文(简体)
Dart Programming - Libraries
  • 时间:2024-12-22

Dart Programming - Libraries


Previous Page Next Page  

A pbrary in a programming language represents a collection of routines (set of programming instructions). Dart has a set of built-in pbraries that are useful to store routines that are frequently used. A Dart pbrary comprises of a set of classes, constants, functions, typedefs, properties, and exceptions.

Importing a pbrary

Importing makes the components in a pbrary 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 pbrary URIs use the dart: scheme to refer to a pbrary. Other pbraries 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 pbrary in Dart is given below −

import  URI 

Consider the following code snippet −

import  dart:io  
import  package:pb1/pbfile.dart  

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

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

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

Some commonly used pbraries are given below −

Sr.No Library & Description
1

dart:io

File, socket, HTTP, and other I/O support for server apppcations. This pbrary does not work in browser-based apppcations. This pbrary is imported by default.

2

dart:core

Built-in types, collections, and other core functionapty for every Dart program. This pbrary is automatically imported.

3

dart: math

Mathematical constants and functions, plus a random number generator.

4

dart: convert

Encoders and decoders for converting between different data representations, including JSON and UTF-8.

5

dart: 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 pbrary dart: math. The snippet calls the sqrt() function from the math pbrary. 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 pbraries 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 pbrary with a private function.

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

Next, import the pbrary

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

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 pbrary. Creating a custom pbrary involves the following steps −

Step 1: Declaring a Library

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

pbrary pbrary_name  
// pbrary contents go here 

Step 2: Associating a Library

You can associate a pbrary in two ways −

    Within the same directory

import  pbrary_name 

    From a different directory

import  dir/pbrary_name 

Example: Custom Library

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

pbrary calculator_pb;  
import  dart:math ; 

//import statement after the pbaray 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 pbrary −

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 pbraries with confpcting identifiers, then you can specify a prefix for one or both pbraries. Use the as keyword for specifying the prefix. The syntax for the same is given below −

Syntax

import  pbrary_uri  as prefix

Example

First, let us define a pbrary: loggerpb.dart.

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

Next, we will define another pbrary: webloggerpb.dart.

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

Finally, we will import the pbrary with a prefix.

import  loggerpb.dart ; 
import  webloggerpb.dart  as web;  

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

It will produce the following output

Log method called in loggerpb msg:hello from loggerpb 
Log method called in webloggerpb msg:hello from webloggerpb 
Advertisements