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.No Exceptions & Description 1 DeferredLoadExceptionThrown when a deferred library fails to load. 2 FormatExceptionException thrown when a string or some other data does not have an expected format and cannot be parsed or processed. 3 IntegerDivisionByZeroExceptionThrown when a number is divided by zero. 4 IOExceptionBase class for all Inupt-Output related exceptions. 5 IsolateSpawnExceptionThrown when an isolate cannot be created. 6 TimeoutThrown 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 − Following are some points to remember − 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. It should produce the following output − 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. It should produce the following output − Example: on…catch The following example shows how to use the on…catch block. It should produce the following output − 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 − The following example illustrates the use of finally block. It should produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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 − Example The following example shows how to use the throw keyword to throw an exception − It should produce the following output − 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 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. 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 −
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 − The important pub commands are as follows − Sr.No Command & 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 − 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. Right-click on the pubsec.yaml and get dependencies. This will internally fire the pub get command as shown below. The downloaded packages and its dependent packages can be verified under the packages folder. Since installation is completed now, we need to refer the dart xml in the project. The syntax is as follows − Read XML String To read XML string and verify the input, Dart XML uses a parse() method. The syntax is as follows − Example : Parsing XML String Input The following example shows how to parse XML string input − It should produce the following output −
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 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 It should produce the following output − An attempt to insert a value other than the specified type will result in a compilation error. The following example illustrates this. Example It should produce the following output − Example: Generic Set It should produce the following output − Example: Generic Queue It should produce the following output − Generic Map A type-safe map declaration specifies the data types of − Syntax Example It should produce the following output −
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.No Dart collection & Description 1 ListA 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. 2 SetSet 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. 3 MapsThe 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. 4 QueueA 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. 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 −
Object
Object-Oriented Programming defines an object as “any entity that has a defined boundary.” An object has the following − 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. It should produce the following output − 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. It should produce the following output − 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. It should produce the following output −
Classes
Dart is an object-oriented language. It supports object-oriented programming features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Dart gives built-in support for this concept called class. Declaring a Class Use the class keyword to declare a class in Dart. A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. The syntax for the same is given below − Syntax The class keyword is followed by the class name. The rules for identifiers must be considered while naming a class. A class definition can include the following − These components put together are termed as the data members of the class. Example: Declaring a class The example declares a class Car. The class has a field named engine. The disp() is a simple function that prints the value of the field engine. Creating Instance of the class To create an instance of the class, use the new keyword followed by the class name. The syntax for the same is given below − Syntax Example: Instantiating a class Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Accessing Attributes and Functions A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot notation (called as the period) to access the data members of a class. Example Take a look at the following example to understand how to access attributes and functions in Dart − The output of the above code is as follows − Dart Constructors A constructor is a special function of the class that is responsible for initializing the variables of the class. Dart defines a constructor with the same name as that of the class. A constructor is a function and hence can be parameterized. However, unlike a function, constructors cannot have a return type. If you don’t declare a constructor, a default no-argument constructor is provided for you. Syntax Example The following example shows how to use constructors in Dart − It should produce the following output − Named Constructors Dart provides named constructors to enable a class define multiple constructors. The syntax of named constructors is as given below − Syntax : Defining the constructor Example The following example shows how you can use named constructors in Dart − It should produce the following output − The this Keyword The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class’s field are the same. Hence to avoid ambiguity, the class’s field is prefixed with the this keyword. The following example explains the same − Example The following example explains how to use the this keyword in Dart − It should produce the following output − Dart Class ─ Getters and Setters Getters and Setters, also called as accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. Getters or accessors are defined using the get keyword. Setters or mutators are defined using the set keyword. A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value. Syntax: Defining a getter Syntax: Defining a setter Example The following example shows how you can use getters and setters in a Dart class − This program code should produce the following output − Class Inheritance Dart supports the concept of Inheritance which is the ability of a program to create new classes from an existing class. The class that is extended to create newer classes is called the parent class/super class. The newly created classes are called the child/sub classes. A class inherits from another class using the ‘extends’ keyword. Child classes inherit all properties and methods except constructors from the parent class. Syntax Note − Dart doesn’t support multiple inheritance. Example: Class Inheritance In the following example, we are declaring a class Shape. The class is extended by the Circle class. Since there is an inheritance relationship between the classes, the child class, i.e., the class Car gets an implicit access to its parent class data member. It should produce the following output − Types of Inheritance Inheritance can be of the following three types − Example The following example shows how multi-level inheritance works − The class Leaf derives the attributes from Root and Child classes by virtue of multi-level inheritance. Its output is as follows − Dart – Class Inheritance and Method Overriding Method Overriding is a mechanism by which the child class redefines a method in its parent class. The following example illustrates the same − Example It should produce the following output − The number and type of the function parameters must match while overriding the method. In case of a mismatch in the number of parameters or their data type, the Dart compiler throws an error. The following illustration explains the same − It should produce the following output − The static Keyword The static keyword can be applied to the data members of a class, i.e., fields and methods. A static variable retains its values till the program finishes execution. Static members are referenced by the class name. Example It should produce the following output − The super Keyword The super keyword is used to refer to the immediate parent of a class. The keyword can be used to refer to the super class version of a variable, property, or method. The following example illustrates the same − Example It should produce the following output −
Interfaces
An interface defines the syntax that any entity must adhere to. Interfaces define a set of methods available on an object. Dart does not have a syntax for declaring interfaces. Class declarations are themselves interfaces in Dart. Classes should use the implements keyword to be able to use an interface. It is mandatory for the implementing class to provide a concrete implementation of all the functions of the implemented interface. In other words, a class must redefine every function in the interface it wishes to implement. Syntax: Implementing an Interface Example In the following program, we are declaring a class Printer. The ConsolePrinter class implements the implicit interface declaration for the Printer class. The main function creates an object of the ConsolePrinter class using the new keyword. This object is used to invoke the function print_data defined in the ConsolePrinter class. It should produce the following output − Implementing Multiple Interfaces A class can implement multiple interfaces. The interfaces are separated by a comma. The syntax for the same is given below − The following example shows how you can implement multiple interfaces in Dart − It should produce the following output −
Functions
Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code. A function declaration tells the compiler about a function’s name, return type, and parameters. A function definition provides the actual body of the function. Sr.No Functions & Description 1 Defining a FunctionA function definition specifies what and how a specific task would be done. 2 Calling a FunctionA function must be called so as to execute it. 3 Returning FunctionsFunctions may also return value along with control, back to the caller. 4 Parameterized FunctionParameters are a mechanism to pass values to functions. Optional Parameters Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function. We have three types of optional parameters in Dart − Sr.No Parameter & Description 1 Optional Positional ParameterTo specify optional positional parameters, use square [] brackets. 2 Optional named parameterUnlike positional parameters, the parameter’s name must be specified while the value is being passed. Curly brace {} can be used to specify optional named parameters. 3 Optional Parameters with Default ValuesFunction parameters can also be assigned values by default. However, such parameters can also be explicitly passed values. Recursive Dart Functions Recursion is a technique for iterating over an operation by having a function call to itself repeatedly until it arrives at a result. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop. Example It should produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Lambda Functions Lambda functions are a concise mechanism to represent functions. These functions are also called as Arrow functions. Syntax Example It should produce the following output −
Enumeration
An enumeration is used for defining named constant values. An enumerated type is declared using the enum keyword. Syntax Where, Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example Example It will produce the following output −
Runes
Strings are a sequence of characters. Dart represents strings as a sequence of Unicode UTF-16 code units. Unicode is a format that defines a unique numeric value for each letter, digit, and symbol. Since a Dart string is a sequence of UTF-16 code units, 32-bit Unicode values within a string are represented using a special syntax. A rune is an integer representing a Unicode code point. The String class in the dart:core library provides mechanisms to access runes. String code units / runes can be accessed in three ways − String.codeUnitAt() Function Code units in a string can be accessed through their indexes. Returns the 16-bit UTF-16 code unit at the given index. Syntax Example It will produce the following output − String.codeUnits Property This property returns an unmodifiable list of the UTF-16 code units of the specified string. Syntax Example It will produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. String.runes Property This property returns an iterable of Unicode code-points of this string.Runes extends iterable. Syntax Example It will produce the following output − Unicode code points are usually expressed as \uXXXX, where XXXX is a 4-digit hexadecimal value. To specify more or less than 4 hex digits, place the value in curly brackets. One can use the constructor of the Runes class in the dart:core library for the same. Example It will produce the following output −