Author: Saim Khalid

  • Libraries

    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: convertEncoders and decoders for converting between different data representations, including JSON and UTF-8.
    5dart: typed_dataLists 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 
    
  • Comprehensions

    List comprehensions are syntactic sugar for looping through enumerables in Elixir. In this chapter we will use comprehensions for iteration and generation.

    Basics

    When we looked at the Enum module in the enumerables chapter, we came across the map function.

    Enum.map(1..3, &(&1 * 2))

    In this example, we will pass a function as the second argument. Each item in the range will be passed into the function, and then a new list will be returned containing the new values.

    Mapping, filtering, and transforming are very common actions in Elixir and so there is a slightly different way of achieving the same result as the previous example −

    for n <- 1..3, do: n * 2

    When we run the above code, it produces the following result −

    [2, 4, 6]
    

    The second example is a comprehension, and as you can probably see, it is simply syntactic sugar for what you can also achieve if you use the Enum.map function. However, there are no real benefits to using a comprehension over a function from the Enum module in terms of performance.

    Comprehensions are not limited to lists but can be used with all enumerables.

    Filter

    You can think of filters as a sort of guard for comprehensions. When a filtered value returns false or nil it is excluded from the final list. Let us loop over a range and only worry about even numbers. We will use the is_even function from the Integer module to check if a value is even or not.

    import Integer
    IO.puts(for x <- 1..10, is_even(x), do: x)

    When the above code is run, it produces the following result −

    [2, 4, 6, 8, 10]
    

    We can also use multiple filters in the same comprehension. Add another filter that you want after the is_even filter separated by a comma.

    :into Option

    In the examples above, all the comprehensions returned lists as their result. However, the result of a comprehension can be inserted into different data structures by passing the :into option to the comprehension.

    For example, a bitstring generator can be used with the :into option in order to easily remove all spaces in a string −

    IO.puts(for <<c <- " hello world ">>, c != ?\s, into: "", do: <<c>>)

    When the above code is run, it produces the following result −

    helloworld
    

    The above code removes all spaces from the string using c != ?\s filter and then using the :into option, it puts all the returned characters in a string.

  • Typedef

    typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function.

    Given below are the steps to implement typedefs in a Dart program.

    Step 1: Defining a typedef

    typedef can be used to specify a function signature that we want specific functions to match. A function signature is defined by a function’s parameters (including their types). The return type is not a part of the function signature. Its syntax is as follows.

    typedef function_name(parameters)
    

    Step 2: Assigning a Function to a typedef Variable

    A variable of typedef can point to any function having the same signature as typedef. You can use the following signature to assign a function to a typedef variable.

    type_def  var_name = function_name
    

    Step 3: Invoking a Function

    The typedef variable can be used to invoke functions. Here is how you can invoke a function −

    var_name(parameters) 
    

    Example

    Let’s now take an example to understand more on typedef in Dart.

    At first, let us define a typedef. Here we are defining a function signature. The function will take two input parameters of the type integer. Return type is not a part of the function signature.

    typedef ManyOperation(int firstNo , int secondNo); //function signature
    

    Next, let us define the functions. Define some functions with the same function signature as that of the ManyOperation typedef.

    Add(int firstNo,int second){ 
       print("Add result is ${firstNo+second}"); 
    }  
    Subtract(int firstNo,int second){ 
       print("Subtract result is ${firstNo-second}"); 
    }  
    Divide(int firstNo,int second){ 
       print("Add result is ${firstNo/second}"); 
    }

    Finally, we will invoke the function via typedef. Declare a variable of the ManyOperations type. Assign the function name to the declared variable.

    ManyOperation oper ;  
    
    //can point to any method of same signature 
    oper = Add; 
    oper(10,20); 
    oper = Subtract; 
    oper(30,20); 
    oper = Divide; 
    oper(50,5); 

    The oper variable can point to any method which takes two integer parameters. The Add function’s reference is assigned to the variable. Typedefs can switch function references at runtime

    Let us now put all the parts together and see the complete program.

    typedef ManyOperation(int firstNo , int secondNo); 
    //function signature  
    
    Add(int firstNo,int second){ 
       print("Add result is ${firstNo+second}"); 
    } 
    Subtract(int firstNo,int second){ 
       print("Subtract result is ${firstNo-second}"); 
    }
    Divide(int firstNo,int second){ 
       print("Divide result is ${firstNo/second}"); 
    }  
    Calculator(int a, int b, ManyOperation oper){ 
       print("Inside calculator"); 
       oper(a,b); 
    }  
    void main(){ 
       ManyOperation oper = Add; 
       oper(10,20); 
       oper = Subtract; 
       oper(30,20); 
       oper = Divide; 
       oper(50,5); 
    } 

    The program should produce the following output −

    Add result is 30 
    Subtract result is 10 
    Divide result is 10.0 
    

    Note − The above code will result in an error if the typedef variable tries to point to a function with a different function signature.

    Example

    Typedefs can also be passed as a parameter to a function. Consider the following example −

    typedef ManyOperation(int firstNo , int secondNo);   //function signature 
    Add(int firstNo,int second){ 
       print("Add result is ${firstNo+second}"); 
    }  
    Subtract(int firstNo,int second){
       print("Subtract result is ${firstNo-second}"); 
    }  
    Divide(int firstNo,int second){ 
       print("Divide result is ${firstNo/second}"); 
    }  
    Calculator(int a,int b ,ManyOperation oper){ 
       print("Inside calculator"); 
       oper(a,b); 
    }  
    main(){ 
       Calculator(5,5,Add); 
       Calculator(5,5,Subtract); 
       Calculator(5,5,Divide); 
    } 

    It will produce the following output −

    Inside calculator 
    Add result is 10 
    Inside calculator 
    Subtract result is 0 
    Inside calculator 
    Divide result is 1.0
    
  • Sigils

    In this chapter, we are going to explore sigils, the mechanisms provided by the language for working with textual representations. Sigils start with the tilde (~) character which is followed by a letter (which identifies the sigil) and then a delimiter; optionally, modifiers can be added after the final delimiter.

    Regex

    Regexes in Elixir are sigils. We have seen their use in the String chapter. Let us again take an example to see how we can use regex in Elixir.

    # A regular expression that matches strings which contain "foo" or
    # "bar":
    regex = ~r/foo|bar/
    IO.puts("foo" =~ regex)
    IO.puts("baz" =~ regex)

    When the above program is run, it produces the following result −

    true
    false
    

    Sigils support 8 different delimiters −

    ~r/hello/
    ~r|hello|
    ~r"hello"
    ~r'hello'
    ~r(hello)
    ~r[hello]
    ~r{hello}
    ~r<hello>
    

    The reason behind supporting different delimiters is that different delimiters can be more suited for different sigils. For example, using parentheses for regular expressions may be a confusing choice as they can get mixed with the parentheses inside the regex. However, parentheses can be handy for other sigils, as we will see in the next section.

    Elixir supports Perl compatible regexes and also support modifiers. You can read up more about the use of regexes here.

    Strings, Char lists and Word lists

    Other than regexes, Elixir has 3 more inbuilt sigils. Let us have a look at the sigils.

    Strings

    The ~s sigil is used to generate strings, like double quotes are. The ~s sigil is useful, for example, when a string contains both double and single quotes −

    new_string = ~s(this is a string with "double" quotes, not 'single' ones)
    IO.puts(new_string)

    This sigil generates strings. When the above program is run, it produces the following result −

    "this is a string with \"double\" quotes, not 'single' ones"
    

    Char Lists

    The ~c sigil is used to generate char lists −

    new_char_list = ~c(this is a char list containing 'single quotes')
    IO.puts(new_char_list)

    When the above program is run, it produces the following result −

    this is a char list containing 'single quotes'
    

    Word Lists

    The ~w sigil is used to generate lists of words (words are just regular strings). Inside the ~w sigil, words are separated by whitespace.

    new_word_list = ~w(foo bar bat)
    IO.puts(new_word_list)

    When the above program is run, it produces the following result −

    foobarbat
    

    The ~w sigil also accepts the c, s and a modifiers (for char lists, strings and atoms, respectively), which specify the data type of the elements of the resulting list −

    new_atom_list = ~w(foo bar bat)a
    IO.puts(new_atom_list)

    When the above program is run, it produces the following result −

    [:foo, :bar, :bat]
    

    Interpolation and Escaping in Sigils

    Besides lowercase sigils, Elixir supports uppercase sigils to deal with escaping characters and interpolation. While both ~s and ~S will return strings, the former allows escape codes and interpolation while the latter does not. Let us consider an example to understand this −

    ~s(String with escape codes \x26 #{"inter" <> "polation"})
    # "String with escape codes & interpolation"
    ~S(String without escape codes \x26 without #{interpolation})
    # "String without escape codes \\x26 without \#{interpolation}"
    

    Custom Sigils

    We can easily create our own custom sigils. In this example, we will create a sigil to convert a string to uppercase.

    defmodule CustomSigil do
       def sigil_u(string, []), do: String.upcase(string)
    end
    
    import CustomSigil
    
    IO.puts(~u/tutorials point/)

    When we run the above code, it produces the following result −

    TUTORIALS POINT
    

    First we define a module called CustomSigil and within that module, we created a function called sigil_u. As there is no existing ~u sigil in the existing sigil space, we will use it. The _u indicates that we wish use u as the character after the tilde. The function definition must take two arguments, an input and a list.

  • Debugging

    Every now and then, developers commit mistakes while coding. A mistake in a program is referred to as a bug. The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks.

    The WebStorm editor enables breakpoints and step-by-step debugging. The program will break at the point where the breakpoint is attached. This functionality is like what you might expect from Java or C# application development. You can watch variables, browse the stack, step over and step into method and function calls, all from the WebStorm Editor.

    Adding a Breakpoint

    Consider the following code snippet. (TestString.dart)

    void main() { 
       int a = 10, b = 20, c = 5; 
       c = c * c * c; 
       
       print("$a + $b = ${a+b}"); 
       print("$a%$b = ${a%b}");  // Add a break point here 
       print("$a*$b = ${a*b}"); 
       print("$a/$b = ${a/b}"); 
       print(c); 
    }

    To add a breakpoint, click on the left margin to. In the figure given below, line number 7 has a break point.

    Add a Breakpoint

    Run the program in debug mode. In the project explorer right click on the dart program in our case TestString.dart.

    Debug TestString

    Once the program runs in debug mode, you will get the Debugger window as shown in the following screenshot. The variables tab shows the values of variables in the current context. You can add watchers for specific variables and listen to that values changes using watches window.

    Add Watchers

    Step Into (F7) arrow icon on debug menu helps to Executes code one statement at a time. If main methods call a subroutine, then this will go into the subroutine code also.

    Step over (F8): It is similar to Step Into. The difference in use occurs when the current statement contains a call to a subroutine. If the main method calls a subroutine, step over will not drill into the subroutine. it will skip the subroutine.

    Step Out (Shift+F8): Executes the remaining lines of a function in which the current execution point lies. The next statement displayed is the statement following the subroutine call.

    After running in debug mode, the program gives the following output −

    10 + 20 = 30 
    10 % 20 = 10 
    10 * 20 = 200 
    10 / 20 = 0.5 
    125
    
  • Exceptions

    An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally.

    Built-in Dart exceptions include −

    Sr.NoExceptions & Description
    1DeferredLoadExceptionThrown when a deferred library fails to load.
    2FormatExceptionException thrown when a string or some other data does not have an expected format and cannot be parsed or processed.
    3IntegerDivisionByZeroExceptionThrown when a number is divided by zero.
    4IOExceptionBase class for all Inupt-Output related exceptions.
    5IsolateSpawnExceptionThrown when an isolate cannot be created.
    6TimeoutThrown when a scheduled timeout happens while waiting for an async result.

    Every exception in Dart is a subtype of the pre-defined class Exception. Exceptions must be handled to prevent the application from terminating abruptly.

    The try / on / catch Blocks

    The try block embeds code that might possibly result in an exception. The on block is used when the exception type needs to be specified. The catch block is used when the handler needs the exception object.

    The try block must be followed by either exactly one on / catch block or one finally block (or one of both). When an exception occurs in the try block, the control is transferred to the catch.

    The syntax for handling an exception is as given below −

    try { 
       // code that might throw an exception 
    }  
    on Exception1 { 
       // code for handling exception 
    }  
    catch Exception2 { 
       // code for handling exception 
    } 
    

    Following are some points to remember −

    • A code snippet can have more than one on / catch blocks to handle multiple exceptions.
    • The on block and the catch block are mutually inclusive, i.e. a try block can be associated with both- the on block and the catch block.

    The following code illustrates exception handling in Dart −

    Example: Using the ON Block

    The following program divides two numbers represented by the variables x and y respectively. The code throws an exception since it attempts division by zero. The on block contains the code to handle this exception.

    main() { 
       int x = 12; 
       int y = 0; 
       int res;  
       
       try {
    
      res = x ~/ y; 
    } on IntegerDivisionByZeroException {
      print('Cannot divide by zero'); 
    } }

    It should produce the following output −

    Cannot divide by zero
    

    Example: Using the catch Block

    In the following example, we have used the same code as above. The only difference is that the catch block (instead of the ON block) here contains the code to handle the exception. The parameter of catch contains the exception object thrown at runtime.

    main() { 
       int x = 12; 
       int y = 0; 
       int res;  
       
       try {  
    
      res = x ~/ y; 
    } catch(e) {
      print(e); 
    } }

    It should produce the following output −

    IntegerDivisionByZeroException
    

    Example: on…catch

    The following example shows how to use the on…catch block.

    main() { 
       int x = 12; 
       int y = 0; 
       int res;  
       
       try { 
    
      res = x ~/ y; 
    } on IntegerDivisionByZeroException catch(e) {
      print(e); 
    } }

    It should produce the following output −

    IntegerDivisionByZeroException
    

    The Finally Block

    The finally block includes code that should be executed irrespective of an exception’s occurrence. The optional finally block executes unconditionally after try/on/catch.

    The syntax for using the finally block is as follows −

    try { 
       // code that might throw an exception 
    }  
    on Exception1 { 
       // exception handling code 
    }  
    catch Exception2 { 
       //  exception handling 
    }  
    finally { 
       // code that should always execute; irrespective of the exception 
    }
    

    The following example illustrates the use of finally block.

    main() { 
       int x = 12; 
       int y = 0; 
       int res;  
       
       try { 
    
      res = x ~/ y; 
    } on IntegerDivisionByZeroException {
      print('Cannot divide by zero'); 
    } finally {
      print('Finally block executed'); 
    } }

    It should produce the following output −

    Cannot divide by zero 
    Finally block executed
    

    Throwing an Exception

    The throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly.

    The syntax for raising an exception explicitly is −

    throw new Exception_name()
    

    Example

    The following example shows how to use the throw keyword to throw an exception −

    main() { 
       try { 
    
      test_age(-2); 
    } catch(e) {
      print('Age cannot be negative'); 
    } } void test_age(int age) { if(age<0) {
      throw new FormatException(); 
    } }

    It should produce the following output −

    Age cannot be negative
    

    Custom Exceptions

    As specified above, every exception type in Dart is a subtype of the built-in class Exception. Dart enables creating custom exceptions by extending the existing ones. The syntax for defining a custom exception is as given below −

    Syntax: Defining the Exception

    class Custom_exception_Name implements Exception { 
       // can contain constructors, variables and methods 
    } 
    

    Custom Exceptions should be raised explicitly and the same should be handled in the code.

    Example

    The following example shows how to define and handle a custom exception.

    class AmtException implements Exception { 
       String errMsg() => 'Amount should be greater than zero'; 
    }  
    void main() { 
       try { 
    
      withdraw_amt(-1); 
    } catch(e) {
      print(e.errMsg()); 
    } finally {
      print('Ending requested operation.....'); 
    } } void withdraw_amt(int amt) { if (amt <= 0) {
      throw new AmtException(); 
    } }

    In the above code, we are defining a custom exception, AmtException. The code raises the exception if the amount passed is not within the excepted range. The main function encloses the function invocation in the try…catch block.

    The code should produce the following output −

    Amount should be greater than zero 
    Ending requested operation.... 
    
  • Packages

    A package is a mechanism to encapsulate a group of programming units. Applications might at times need integration of some third-party libraries or plugins. Every language has a mechanism for managing external packages like Maven or Gradle for Java, Nuget for .NET, npm for Node.js, etc. The package manager for Dart is pub.

    Pub helps to install packages in the repository. The repository of packages hosted can be found at https://pub.dartlang.org/.

    The package metadata is defined in a file, pubsec.yaml. YAML is the acronym for Yet Another Markup Language. The pub tool can be used to download all various libraries that an application requires.

    Every Dart application has a pubspec.yaml file which contains the application dependencies to other libraries and metadata of applications like application name, author, version, and description.

    The contents of a pubspec.yaml file should look something like this −

    name: 'vector_victor' 
    version: 0.0.1 
    description: An absolute bare-bones web app. 
    ... 
    dependencies: browser: '>=0.10.0 <0.11.0' 
    

    The important pub commands are as follows −

    Sr.NoCommand & Description
    1‘pub get’Helps to get all packages your application is depending on.
    2‘pub upgrade’Upgrades all your dependencies to a newer version.
    3‘pub build’This s used for building your web application and it will create a build folder , with all related scripts in it.
    4‘pub help’This will give you help for all different pub commands.

    If you are using an IDE like WebStorm, then you can right-click on the pubspec.yaml to get all the commands directly −

    Pubspec.yaml

    Installing a Package

    Consider an example where an application needs to parse xml. Dart XML is a lightweight library that is open source and stable for parsing, traversing, querying and building XML documents.

    The steps for achieving the said task is as follows −

    Step 1 − Add the following to the pubsec.yaml file.

    name: TestApp 
    version: 0.0.1 
    description: A simple console application. 
    #dependencies: 
    #  foo_bar: '>=1.0.0 <2.0.0' 
    dependencies: https://mail.google.com/mail/u/0/images/cleardot.gif
    xml: 

    Right-click on the pubsec.yaml and get dependencies. This will internally fire the pub get command as shown below.

    Pub Get Command

    The downloaded packages and its dependent packages can be verified under the packages folder.

    Packages

    Since installation is completed now, we need to refer the dart xml in the project. The syntax is as follows −

    import 'package:xml/xml.dart' as xml;
    

    Read XML String

    To read XML string and verify the input, Dart XML uses a parse() method. The syntax is as follows −

    xml.parse(String input):
    

    Example : Parsing XML String Input

    The following example shows how to parse XML string input −

    import 'package:xml/xml.dart' as xml; 
    void main(){ 
       print("xml"); 
       var bookshelfXml = '''<?xml version = "1.0"?> 
       <bookshelf> 
    
      &lt;book&gt; 
         &lt;title lang = "english"&gt;Growing a Language&lt;/title&gt; 
         &lt;price&gt;29.99&lt;/price&gt; 
      &lt;/book&gt; 
      
      &lt;book&gt; 
         &lt;title lang = "english"&gt;Learning XML&lt;/title&gt; 
         &lt;price&gt;39.95&lt;/price&gt; 
      &lt;/book&gt; 
      &lt;price&gt;132.00&lt;/price&gt; 
    </bookshelf>'''; var document = xml.parse(bookshelfXml); print(document.toString()); }

    It should produce the following output −

    xml 
    <?xml version = "1.0"?><bookshelf> 
       <book> 
    
      &lt;title lang = "english"&gt;Growing a Language&lt;/title&gt; 
      &lt;price&gt;29.99&lt;/price&gt; 
    </book> <book>
      &lt;title lang = "english"&gt;Learning XML&lt;/title&gt; 
      &lt;price&gt;39.95&lt;/price&gt; 
    </book> <price>132.00</price> </bookshelf>
  • Generics

    Dart is an optionally typed language. Collections in Dart are heterogeneous by default. In other words, a single Dart collection can host values of various types. However, a Dart collection can be made to hold homogenous values. The concept of Generics can be used to achieve the same.

    The use of Generics enforces a restriction on the data type of the values that can be contained by the collection. Such collections are termed as type-safe collections. Type safety is a programming feature which ensures that a memory block can only contain data of a specific data type.

    All Dart collections support type-safety implementation via generics. A pair of angular brackets containing the data type is used to declare a type-safe collection. The syntax for declaring a type-safe collection is as given below.

    Syntax

    Collection_name <data_type> identifier= new Collection_name<data_type> 
    

    The type-safe implementations of List, Map, Set and Queue is given below. This feature is also supported by all implementations of the above-mentioned collection types.

    Example: Generic List

    void main() { 
       List <String> logTypes = new List <String>(); 
       logTypes.add("WARNING"); 
       logTypes.add("ERROR"); 
       logTypes.add("INFO");  
       
       // iterating across list 
       for (String type in logTypes) { 
    
      print(type); 
    } }

    It should produce the following output −

    WARNING 
    ERROR 
    INFO
    

    An attempt to insert a value other than the specified type will result in a compilation error. The following example illustrates this.

    Example

    void main() { 
       List <String> logTypes = new List <String>(); 
       logTypes.add(1); 
       logTypes.add("ERROR"); 
       logTypes.add("INFO"); 
      
       //iterating across list 
       for (String type in logTypes) { 
    
      print(type); 
    } }

    It should produce the following output −

    1                                                                                     
    ERROR                                                                             
    INFO
    

    Example: Generic Set

    void main() { 
       Set <int>numberSet = new  Set<int>(); 
       numberSet.add(100); 
       numberSet.add(20); 
       numberSet.add(5); 
       numberSet.add(60);
       numberSet.add(70); 
       
       // numberSet.add("Tom"); 
       compilation error; 
       print("Default implementation  :${numberSet.runtimeType}");  
       
       for(var no in numberSet) { 
    
      print(no); 
    } }

    It should produce the following output −

    Default implementation :_CompactLinkedHashSet<int> 
    100 
    20 
    5 
    60 
    70
    

    Example: Generic Queue

    import 'dart:collection'; 
    void main() { 
       Queue<int> queue = new Queue<int>(); 
       print("Default implementation ${queue.runtimeType}");  
       queue.addLast(10); 
       queue.addLast(20); 
       queue.addLast(30); 
       queue.addLast(40); 
       queue.removeFirst();  
       
       for(int no in queue){ 
    
      print(no); 
    } }

    It should produce the following output −

    Default implementation ListQueue<int> 
    20 
    30 
    40
    

    Generic Map

    A type-safe map declaration specifies the data types of −

    • The key
    • The value

    Syntax

    Map <Key_type, value_type>
    

    Example

    void main() { 
       Map <String,String>m={'name':'Tom','Id':'E1001'}; 
       print('Map :${m}'); 
    } 

    It should produce the following output −

    Map :{name: Tom, Id: E1001}
    
  • Collection

    Dart, unlike other programming languages, doesn’t support arrays. Dart collections can be used to replicate data structures like an array. The dart:core library and other classes enable Collection support in Dart scripts.

    Dart collections can be basically classified as −

    Sr.NoDart collection & Description
    1ListA List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists.Fixed Length List − The list’s length cannot change at run-time.Growable List − The list’s length can change at run-time.
    2SetSet represents a collection of objects in which each object can occur only once. The dart:core library provides the Set class to implement the same.
    3MapsThe Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection. In other words, Maps can grow and shrink at runtime. The Map class in the dart:core library provides support for the same.
    4QueueA Queue is a collection that can be manipulated at both ends. Queues are useful when you want to build a first-in, first-out collection. Simply put, a queue inserts data from one end and deletes from another end. The values are removed / read in the order of their insertion.

    Iterating Collections

    The Iterator class from the dart:core library enables easy collection traversal. Every collection has an iterator property. This property returns an iterator that points to the objects in the collection.

    Example

    The following example illustrates traversing a collection using an iterator object.

    import 'dart:collection'; 
    void main() { 
       Queue numQ = new Queue(); 
       numQ.addAll([100,200,300]);  
       Iterator i= numQ.iterator; 
       
       while(i.moveNext()) { 
    
      print(i.current); 
    } }

    The moveNext() function returns a Boolean value indicating whether there is a subsequent entry. The current property of the iterator object returns the value of the object that the iterator currently points to.

    This program should produce the following output −

    100 
    200 
    300
    
  • Object

    Object-Oriented Programming defines an object as “any entity that has a defined boundary.” An object has the following −

    • State − Describes the object. The fields of a class represent the object’s state.
    • Behavior − Describes what an object can do.
    • Identity − A unique value that distinguishes an object from a set of similar other objects. Two or more objects can share the state and behavior but not the identity.

    The period operator (.) is used in conjunction with the object to access a class’ data members.

    Example

    Dart represents data in the form of objects. Every class in Dart extends the Object class. Given below is a simple example of creating and using an object.

    class Student { 
       void test_method() { 
    
      print("This is a  test method"); 
    } void test_method1() {
      print("This is a  test method1"); 
    } } void main() { Student s1 = new Student(); s1.test_method(); s1.test_method1(); }

    It should produce the following output −

    This is a test method 
    This is a test method1
    

    The Cascade operator (..)

    The above example invokes the methods in the class. However, every time a function is called, a reference to the object is required. The cascade operator can be used as a shorthand in cases where there is a sequence of invocations.

    The cascade ( .. ) operator can be used to issue a sequence of calls via an object. The above example can be rewritten in the following manner.

    class Student { 
       void test_method() { 
    
      print("This is a  test method"); 
    } void test_method1() {
      print("This is a  test method1"); 
    } } void main() { new Student() ..test_method() ..test_method1(); }

    It should produce the following output −

    This is a test method 
    This is a test method1
    

    The toString() method

    This function returns a string representation of an object. Take a look at the following example to understand how to use the toString method.

    void main() { 
       int n = 12; 
       print(n.toString()); 
    } 

    It should produce the following output −

    12