Dart Programming – Libraries

Dart Programming – Libraries ”; Previous Next 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.No Library & Description 1 dart:io File, 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. 2 dart:core Built-in types, collections, and other core functionality for every Dart program. This library 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 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. Live Demo 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. Live Demo 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 Print Page Previous Next Advertisements ”;

Dart Programming – Data Types

Dart Programming – Data Types ”; Previous Next One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language. The Dart language supports the following types− Numbers Strings Booleans Lists Maps Numbers Numbers in Dart are used to represent numeric literals. The Number Dart come in two flavours − Integer − Integer values represent non-fractional values, i.e., numeric values without a decimal point. For example, the value “10” is an integer. Integer literals are represented using the int keyword. Double − Dart also supports fractional numeric values i.e. values with decimal points. The Double data type in Dart represents a 64-bit (double-precision) floating-point number. For example, the value “10.10”. The keyword double is used to represent floating point literals. Strings Strings represent a sequence of characters. For instance, if you were to store some data like name, address etc. the string data type should be used. A Dart string is a sequence of UTF-16 code units. Runes are used to represent a sequence of UTF-32 code units. The keyword String is used to represent string literals. String values are embedded in either single or double quotes. Boolean The Boolean data type represents Boolean values true and false. Dart uses the bool keyword to represent a Boolean value. List and Map The data types list and map are used to represent a collection of objects. A List is an ordered group of objects. The List data type in Dart is synonymous to the concept of an array in other programming languages. The Map data type represents a set of values as key-value pairs. The dart: core library enables creation and manipulation of these collections through the predefined List and Map classes respectively. The Dynamic Type Dart is an optionally typed language. If the type of a variable is not explicitly specified, the variable’s type is dynamic. The dynamic keyword can also be used as a type annotation explicitly. Print Page Previous Next Advertisements ”;

Dart Programming – Async

Dart Programming – Async ”; Previous Next An asynchronous operation executes in a thread, separate from the main application thread. When an application calls a method to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task. Example Let’s take an example to understand this concept. Here, the program accepts user input using the IO library. Live Demo import ”dart:io”; void main() { print(“Enter your name :”); // prompt for user input String name = stdin.readLineSync(); // this is a synchronous method that reads user input print(“Hello Mr. ${name}”); print(“End of main”); } The readLineSync() is a synchronous method. This means that the execution of all instructions that follow the readLineSync() function call will be blocked till the readLineSync() method finishes execution. The stdin.readLineSync waits for input. It stops in its tracks and does not execute any further until it receives the user’s input. The above example will result in the following output − Enter your name : Tom // reads user input Hello Mr. Tom End of main In computing, we say something is synchronous when it waits for an event to happen before continuing. A disadvantage in this approach is that if a part of the code takes too long to execute, the subsequent blocks, though unrelated, will be blocked from executing. Consider a webserver that must respond to multiple requests for a resource. A synchronous execution model will block every other user’s request till it finishes processing the current request. In such a case, like that of a web server, every request must be independent of the others. This means, the webserver should not wait for the current request to finish executing before it responds to request from other users. Simply put, it should accept requests from new users before necessarily completing the requests of previous users. This is termed as asynchronous. Asynchronous programming basically means no waiting or non-blocking programming model. The dart:async package facilitates implementing asynchronous programming blocks in a Dart script. Example The following example better illustrates the functioning of an asynchronous block. Step 1 − Create a contact.txt file as given below and save it in the data folder in the current project. 1, Tom 2, John 3, Tim 4, Jane Step 2 − Write a program which will read the file without blocking other parts of the application. import “dart:async”; import “dart:io”; void main(){ File file = new File( Directory.current.path+”\data\contact.txt”); Future<String> f = file.readAsString(); // returns a futrue, this is Async method f.then((data)=>print(data)); // once file is read , call back method is invoked print(“End of main”); // this get printed first, showing fileReading is non blocking or async } The output of this program will be as follows − End of main 1, Tom 2, John 3, Tim 4, Jan The “end of main” executes first while the script continues reading the file. The Future class, part of dart:async, is used for getting the result of a computation after an asynchronous task has completed. This Future value is then used to do something after the computation finishes. Once the read operation is completed, the execution control is transferred within “then()”. This is because the reading operation can take more time and so it doesn’t want to block other part of program. Dart Future The Dart community defines a Future as “a means for getting a value sometime in the future.” Simply put, Future objects are a mechanism to represent values returned by an expression whose execution will complete at a later point in time. Several of Dart’s built-in classes return a Future when an asynchronous method is called. Dart is a single-threaded programming language. If any code blocks the thread of execution (for example, by waiting for a time-consuming operation or blocking on I/O), the program effectively freezes. Asynchronous operations let your program run without getting blocked. Dart uses Future objects to represent asynchronous operations. Print Page Previous Next Advertisements ”;

Dart Programming – Symbol

Dart Programming – Symbol ”; Previous Next Symbols in Dart are opaque, dynamic string name used in reflecting out metadata from a library. Simply put, symbols are a way to store the relationship between a human readable string and a string that is optimized to be used by computers. Reflection is a mechanism to get metadata of a type at runtime like the number of methods in a class, the number of constructors it has or the number of parameters in a function. You can even invoke a method of the type which is loaded at runtime. In Dart reflection specific classes are available in the dart:mirrors package. This library works in both web applications and command line applications. Syntax Symbol obj = new Symbol(”name”); // expects a name of class or function or library to reflect The name must be a valid public Dart member name, public constructor name, or library name. Example Consider the following example. The code declares a class Foo in a library foo_lib. The class defines the methods m1, m2, and m3. Foo.dart library foo_lib; // libarary name can be a symbol class Foo { // class name can be a symbol m1() { // method name can be a symbol print(“Inside m1”); } m2() { print(“Inside m2”); } m3() { print(“Inside m3″); } } The following code loads Foo.dart library and searches for Foo class, with help of Symbol type. Since we are reflecting the metadata from the above library the code imports dart:mirrors library. FooSymbol.dart import ”dart:core”; import ”dart:mirrors”; import ”Foo.dart”; main() { Symbol lib = new Symbol(“foo_lib”); //library name stored as Symbol Symbol clsToSearch = new Symbol(“Foo”); // class name stored as Symbol if(checkIf_classAvailableInlibrary(lib, clsToSearch)) // searches Foo class in foo_lib library print(“class found..”); } bool checkIf_classAvailableInlibrary(Symbol libraryName, Symbol className) { MirrorSystem mirrorSystem = currentMirrorSystem(); LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); if (libMirror != null) { print(“Found Library”); print(“checkng…class details..”); print(“No of classes found is : ${libMirror.declarations.length}”); libMirror.declarations.forEach((s, d) => print(s)); if (libMirror.declarations.containsKey(className)) return true; return false; } } Note that the line libMirror.declarations.forEach((s, d) => print(s)); will iterate across every declaration in the library at runtime and prints the declarations as type of Symbol. This code should produce the following output − Found Library checkng…class details.. No of classes found is : 1 Symbol(“Foo”) // class name displayed as symbol class found. Example: Display the number of instance methods of a class Let us now consider displaying the number of instance methods in a class. The predefined class ClassMirror helps us to achieve the same. import ”dart:core”; import ”dart:mirrors”; import ”Foo.dart”; main() { Symbol lib = new Symbol(“foo_lib”); Symbol clsToSearch = new Symbol(“Foo”); reflect_InstanceMethods(lib, clsToSearch); } void reflect_InstanceMethods(Symbol libraryName, Symbol className) { MirrorSystem mirrorSystem = currentMirrorSystem(); LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); if (libMirror != null) { print(“Found Library”); print(“checkng…class details..”); print(“No of classes found is : ${libMirror.declarations.length}”); libMirror.declarations.forEach((s, d) => print(s)); if (libMirror.declarations.containsKey(className)) print(“found class”); ClassMirror classMirror = libMirror.declarations[className]; print(“No of instance methods found is ${classMirror.instanceMembers.length}”); classMirror.instanceMembers.forEach((s, v) => print(s)); } } This code should produce the following output − Found Library checkng…class details.. No of classes found is : 1 Symbol(“Foo”) found class No of instance methods found is 8 Symbol(“==”) Symbol(“hashCode”) Symbol(“toString”) Symbol(“noSuchMethod”) Symbol(“runtimeType”) Symbol(“m1”) Symbol(“m2”) Symbol(“m3″) Convert Symbol to String You can convert the name of a type like class or library stored in a symbol back to string using MirrorSystem class. The following code shows how you can convert a symbol to a string. Live Demo import ”dart:mirrors”; void main(){ Symbol lib = new Symbol(“foo_lib”); String name_of_lib = MirrorSystem.getName(lib); print(lib); print(name_of_lib); } It should produce the following output − Symbol(“foo_lib”) foo_lib Print Page Previous Next Advertisements ”;

Dart Programming – Syntax

Dart Programming – Syntax ”; Previous Next Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. A Dart program is composed of − Variables and Operators Classes Functions Expressions and Programming Constructs Decision Making and Looping Constructs Comments Libraries and Packages Typedefs Data structures represented as Collections / Generics Your First Dart Code Let us start with the traditional “Hello World” example − Live Demo main() { print(“Hello World!”); } The main() function is a predefined method in Dart. This method acts as the entry point to the application. A Dart script needs the main() method for execution. print() is a predefined function that prints the specified string or value to the standard output i.e. the terminal. The output of the above code will be − Hello World! Execute a Dart Program You can execute a Dart program in two ways − Via the terminal Via the WebStorm IDE Via the Terminal To execute a Dart program via the terminal − Navigate to the path of the current project Type the following command in the Terminal window dart file_name.dart Via the WebStorm IDE To execute a Dart program via the WebStorm IDE − Right-click the Dart script file on the IDE. (The file should contain the main() function to enable execution) Click on the ‘Run <file_name>’ option. A screenshot of the same is given below − One can alternatively click the button or use the shortcut Ctrl+Shift+F10 to execute the Dart Script. Dart Command-Line Options Dart command-line options are used to modify Dart Script execution. Common commandline options for Dart include the following − Sr.No Command-Line Option & Description 1 -c or –c Enables both assertions and type checks (checked mode). 2 –version Displays VM version information. 3 –packages <path> Specifies the path to the package resolution configuration file. 4 -p <path> Specifies where to find imported libraries. This option cannot be used with –packages. 5 -h or –help Displays help. Enabling Checked Mode Dart programs run in two modes namely − Checked Mode Production Mode (Default) It is recommended to run the Dart VM in checked mode during development and testing, since it adds warnings and errors to aid development and debugging process. The checked mode enforces various checks like type-checking etc. To turn on the checked mode, add the -c or –-checked option before the script-file name while running the script. However, to ensure performance benefit while running the script, it is recommended to run the script in the production mode. Consider the following Test.dart script file − Live Demo void main() { int n = “hello”; print(n); } Run the script by entering − dart Test.dart Though there is a type-mismatch the script executes successfully as the checked mode is turned off. The script will result in the following output − hello Now try executing the script with the “- – checked” or the “-c” option − dart -c Test.dart Or, dart – – checked Test.dart The Dart VM will throw an error stating that there is a type mismatch. Unhandled exception: type ”String” is not a subtype of type ”int” of ”n” where String is from dart:core int is from dart:core #0 main (file:///C:/Users/Administrator/Desktop/test.dart:3:9) #1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart :261) #2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148) Identifiers in Dart Identifiers are names given to elements in a program like variables, functions etc. The rules for identifiers are − Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit. Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($). Identifiers cannot be keywords. They must be unique. Identifiers are case-sensitive. Identifiers cannot contain spaces. The following tables lists a few examples of valid and invalid identifiers − Valid identifiers Invalid identifiers firstName Var first_name first name num1 first-name $result 1number Keywords in Dart Keywords have a special meaning in the context of a language. The following table lists some keywords in Dart. abstract 1 continue false new this as 1 default final null throw assert deferred 1 finally operator 1 true async 2 do for part 1 try async* 2 dynamic 1 get 1 rethrow typedef 1 await 2 else if return var break enum implements 1 set 1 void case export 1 import 1 static 1 while catch external 1 in super with class extends is switch yield 2 const factory 1 library 1 sync* 2 yield* 2 Whitespace and Line Breaks Dart ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand. Dart is Case-sensitive Dart is case-sensitive. This means that Dart differentiates between uppercase and lowercase characters. Statements end with a Semicolon Each line of instruction is called a statement. Each dart statement must end with a semicolon (;). A single line can contain multiple statements. However, these statements must be separated by a semicolon. Comments in Dart Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct etc. Comments are ignored by the compiler. Dart supports the following types of comments − Single-line comments ( // ) − Any text between a “//” and the end of a line is treated as a comment Multi-line comments (/* */) − These comments may span multiple lines. Example // this is single line comment /* This is a Multi-line comment */ Object-Oriented Programming in Dart Dart is an Object-Oriented language. Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods. Object − An object is a real-time representation of any entity. As per Grady Brooch, every object must have three features −

Dart Programming – Variables

Dart Programming – Variables ”; Previous Next A variable is “a named space in the memory” that stores values. In other words, it acts a container for values in a program. Variable names are called identifiers. Following are the naming rules for an identifier − Identifiers cannot be keywords. Identifiers can contain alphabets and numbers. Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign. Variable names cannot begin with a number. Type Syntax A variable must be declared before it is used. Dart uses the var keyword to achieve the same. The syntax for declaring a variable is as given below − var name = ”Smith”; All variables in dart store a reference to the value rather than containing the value. The variable called name contains a reference to a String object with a value of “Smith”. Dart supports type-checking by prefixing the variable name with the data type. Type-checking ensures that a variable holds only data specific to a data type. The syntax for the same is given below − String name = ”Smith”; int num = 10; Consider the following example − void main() { String name = 1; } The above snippet will result in a warning since the value assigned to the variable doesn’t match the variable’s data type. Output Warning: A value of type ”String” cannot be assigned to a variable of type ”int” All uninitialized variables have an initial value of null. This is because Dart considers all values as objects. The following example illustrates the same − Live Demo void main() { int num; print(num); } Output Null The dynamic keyword Variables declared without a static type are implicitly declared as dynamic. Variables can be also declared using the dynamic keyword in place of the var keyword. The following example illustrates the same. Live Demo void main() { dynamic x = “tom”; print(x); } Output tom Final and Const The final and const keyword are used to declare constants. Dart prevents modifying the values of a variable declared using the final or const keyword. These keywords can be used in conjunction with the variable’s data type or instead of the var keyword. The const keyword is used to represent a compile-time constant. Variables declared using the const keyword are implicitly final. Syntax: final Keyword final variable_name OR final data_type variable_name Syntax: const Keyword const variable_name OR const data_type variable_name Example – final Keyword Live Demo void main() { final val1 = 12; print(val1); } Output 12 Example – const Keyword void main() { const pi = 3.14; const area = pi*12*12; print(“The output is ${area}”); } The above example declares two constants, pi and area, using the const keyword. The area variable’s value is a compile-time constant. Output The output is 452.15999999999997 Note − Only const variables can be used to compute a compile time constant. Compile-time constants are constants whose values will be determined at compile time Example Dart throws an exception if an attempt is made to modify variables declared with the final or const keyword. The example given below illustrates the same − Live Demo void main() { final v1 = 12; const v2 = 13; v2 = 12; } The code given above will throw the following error as output − Unhandled exception: cannot assign to final variable ”v2=”. NoSuchMethodError: cannot assign to final variable ”v2=” #0 NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:178) #1 main (file: Test.dart:5:3) #2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) #3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148) Print Page Previous Next Advertisements ”;