Share
Flutter Mobile App. Development

Course Outline

Week 1
Week 2
Week 3
Week 4

Dart Programming

  • Functions
  • Interfaces
  • Classes
  • Packages
  • Libraries
  • Async
Week 5
Week 6
Week 7
Week 8
Week 9
Week 10
Week 11
Week 12
Week 13

SponsoredAdvertise

Function


A function is a block of code which performs a specific task.


Function Structure


A function has a data type, a name and or parameter(s). The data type is the same as the variable data type or void. When a function returns a particular data, the data type of the function is the type of data type it returns. For instance if a function will return a double value whenever it is called to perform a specific task, then the data type of the function must be double and if the return value will be int, then data type of the function must be int and so on. The data type for a function which doesn't return a value is void

Functions are name just as we name variables. It follows the same naming rules. They must contain only letters and or numbers and no special characters except underscore and must not contain any space in them and can't start with a digit. The name you choose to use for a function should reflect the kind of task the function is performing so it will be easier for people to understand your code or for you yourself to comprehend your code later when you want to update your code.


Syntax


data type functionName(parameter(s) or no parameter){

        //Code to perform the task comes here

       return value; // value data type should be the same as the function data type

}


Examples


A function to calculate the sum of two numbers could be written as:


double sum(double a, double b){

          return a+b;

}

int sum(int a, int b){

return a+b;

}


A function to calculate the square of a number could be written as:


double square(double a){

return a * a;

}


A function to print a greeting message on the screen could be written as:


void greet(String name,String time){

     print("Good $time, $name"); 

     // function doesn't return a value. 

     // Simply prints out something to the screen

}


The void return function example is what you've been seeing a lot in your dart programs that you've been writing for the past weeks.


Thus:


void main(){

}


It doesn't return any value after the function is executed and doesn't have parameter neither.


Functions are written outside the main function.


Function Call


The function call in the assignment statement activates the code for function. You activate a function by writing a function call. The function call is simply writing the function name and passing the appropriate function parameters.  After the function executes, the function result (return value if there is any) is substituted for the function call. If a function has parameter(s), you have to pass the appropriate parameters to that function. Otherwise you will get a syntax error.


Examples


void main(){
    double a,b,c;
    a = 20;
    b = 25.5;
    c = sum(a,b);
    print("$a + $b = $c");
    String name = "Joseph Mensah";
    greet(name,"Morning");
    int d,e;
    d = 4;
    e = square(d);
    print("The square of $d is $e");
    double f;
    f = difference(a,b);
    print("The difference of $a and $b is $f");
  }
  double sum(double a, double b){
    return a+b;
  }
  void greet(String name,String time){
    print("Good $time, $name");
  }
  int square(int a){
    return a*a;
  }
  double difference(double a, double b){
    return a-b;
  }


Output


20 + 25.5 = 45.5

Good Morning, Joseph Mensah

The square of 4 is 16

The difference of 20 and 25.5 is -5.5


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


void main() { 
   print(factorial(5));
}  
factorial(number) { 
   if (number <= 0) {         
      // termination case 
      return 1; 
   } else { 
      return (number * factorial(number - 1));    
      // function invokes itself 
   } 
}   


It should produce the following output −


120


Lambda Functions


Lambda functions are a concise mechanism to represent functions. These functions are also called as Arrow functions.


Syntax


[return_type]function_name(parameters)=>expression;


Example


void main() { 
   sayHello("Godwin"); 
   print(sum(5,7)); 
}  
sayHello(String name)=>print("Hello "+name); 
int sum(int a, int b)=>a+b;


It should produce the following output −


Hello Godwin

12 


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

class identifier implements interface_name


We will first introduce the class topic now and illustrate the interface for the classes.


Class


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

class class_name {  

}


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 −


Fields − A field is any variable declared in a class. Fields represent data pertaining to objects.


Setters and Getters − Allows the program to initialize and retrieve the values of the fields of a class. A default getter/ setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter.


Constructors − responsible for allocating memory for the objects of the class.


Functions − Functions represent actions an object can take. They are also at times referred to as methods.


These components put together are termed as the data members of the class.


NB: Even though you can give a name to a class which follows the same rules of variable declaration, it is recommended to start a class name with a capital letter and object names with small letter.


Example: Declaring a class


class Person{
  //Fields - Data for the class comes here
   String firstname,lastname,address,phone;
   int age;
  //Constructor of the class comes here
  //Functions (methods) come here
   void printName(){
     print("$firstname $lastname");
   }
}


The example declares a class Person. The class has a field named firstname,lastname,address and phone. 

The printName() function simply prints out the name of the person


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

var object_name = new className ([ arguments ])

or

className object_name = new ClassName([Arguments])


The new keyword is responsible for instantiation.


To instantiate a class means creating object of the class. Like it is defined earlier on that a class is a blueprint for creating objects. So you can create as many objects as you wish from the class. Classes makes it possible to reuse codes. You don't have to create an entire code to perform a task you have already written. You can simply create object of the class to have the same features (data and functions) as the class they were created from.


The right-hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized. If the class doesn't have parameter(s) to pass when creating the class, the constructor will have empty argument thus ().


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

Class_name(parameter_list) { 

   //constructor body 

}


Example


Let's create a constructor for our Person class. Any time the Person class is instantiated, we will make it that the variable values are passed in the constructor to initialize our fields (variable data).


void main() { 
   Person person = new Person("Godwin","Ashong","Mango street D44, Teshie - Accra","+233241293039");
  
}

class Person{
  //Fields - Data for the class comes here
   String firstname,lastname,address,phone;
   int age;
  //Constructor of the class comes here
  Person(String fn, String ln, String addr, String ph){
    firstname = fn;
    lastname = ln;
    address = addr;
    phone = ph;
  }
  //Functions (methods) come here
   void printName(){
     print("$firstname $lastname");
   }
}



Accessing a class function 


Class functions can be accessed using the dot after the object name and writing the function name and its arguments. Thus


object_name.functionName(argument);


We can therefore modify our Person class code for the object to call the printName() function. The modified code is shown below:


void main() { 
   Person person = new Person("Godwin","Ashong","Mango street D44, Teshie - Accra","+233241293039");
  person.printName();
}

class Person{
  //Fields - Data for the class comes here
   String firstname,lastname,address,phone;
   int age;
  //Constructor of the class comes here
  Person(String fn, String ln, String addr, String ph){
    firstname = fn;
    lastname = ln;
    address = addr;
    phone = ph;
  }
  //Functions (methods) come here
   void printName(){
     print("$firstname $lastname");
   }
}


When run the output will be:

Godwin Ashong


Named Constructors


Dart provides named constructors to enable a class define multiple constructors. The syntax of named constructors is as given below −


className.namedConstructor(arguments)


NB: It is recommended to start the name constructor with a lower case.


Let's modify our Person class with a named constructor which takes more information than the actual constructor. And take note of the use of the this keyword.


void main() { 
   Person person = new Person("Godwin","Ashong","Mango street D44, Teshie - Accra","+233241293039");
  person.printName();
  Person complete_person = new Person.complete("Godwin","Ashong","Mango street D44, Teshie - Accra","+233241293039","Lekma 12","Teshie Presec","KNUST");
  complete_person.educationalBackground();
}

class Person{
  //Fields - Data for the class comes here
   String firstname,lastname,address,phone,jhs,shs,university;
   int age;
  //Constructor of the class comes here
  Person(String fn, String ln, String addr, String ph){
    firstname = fn;
    lastname = ln;
    address = addr;
    phone = ph;
  }
  Person.complete(String fn, String ln, String addr, String ph, String jhs,String shs, String university){
    firstname = fn;
    lastname = ln;
    address = addr;
    phone = ph;
    this.jhs = jhs;
    this.shs = shs;
    this.university = university;
  }
  //Functions (methods) come here
   void printName(){
     print("$firstname $lastname");
   }
  void educationalBackground(){
    print("JHS: $jhs SHS:$shs UNIVERSITY:$university");
  }
}


When run should output:


Godwin Ashong

JHS: Lekma 12 SHS:Teshie Presec UNIVERSITY:KNUST


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 −


In the above named constructor, the jhs,shs and university parameters for the named constructor is the same as the class data variables (jhs,shs and university). Hence to avoid ambiguity, the keyword this is used to differentiate them from the parameter variables. Thus in the code:


this.jhs = jhs;
this.shs = shs;
this.university = university;


So the variables with the this keyword refers to the variable of the class and the one without the this refers the parameter variables.


We can modify the person class so that the parameter variables have the same names as the class variables so we use the this keyword on the class variables in the constructor.


The modified code is shown below:


void main() { 
   Person person = new Person("Godwin","Ashong","Mango street D44, Teshie - Accra","+233241293039");
  person.printName();
  Person complete_person = new Person.complete("Godwin","Ashong","Mango street D44, Teshie - Accra","+233241293039","Lekma 12","Teshie Presec","KNUST");
  complete_person.educationalBackground();
}

class Person{
  //Fields - Data for the class comes here
   String firstname,lastname,address,phone,jhs,shs,university;
   int age;
  //Constructor of the class comes here
  Person(String firstname, String lastname, String address, String phone){
    this.firstname = firstname;
    this.lastname = lastname;
    this.address = address;
    this.phone = phone;
  }
  Person.complete(String firstname, String lastname, String address, String phone, String jhs,String shs, String university){
    this.firstname = firstname;
    this.lastname = lastname;
    this.address = address;
    this.phone = phone;
    this.jhs = jhs;
    this.shs = shs;
    this.university = university;
  }
  //Functions (methods) come here
   void printName(){
     print("$firstname $lastname");
   }
  void educationalBackground(){
    print("JHS: $jhs SHS:$shs UNIVERSITY:$university");
  }
}


Getters and Setters of a class


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

Return_type  get identifier 

Syntax: Defining a setter

set identifier 

}


Let's modify our Person class so we use setters to set the class variable values and getters to retrive the variable values set instead of using a constructor to set the values.


The modified code is shown below:


void main() { 
   Person person = new Person();
   //Set the values
   person.setFirstName("Godwin");
  person.setLastName("Ashong");
  person.setAddress("Mango street D44, Teshie - Accra, Ghana");
  person.setPhone("+233203930303");
  person.setAge(22);
  person.setJHS("Pre-vas Royal Kids");
  person.setSHS("Teshie - Presec");
  person.setUniversity("KNUST");
  //Get the set values and print out the results
  print("PERSONAL INFORMATION");
  print("First Name:"+person.getFirstName());
  print("Last Name:"+person.getLastName());
  print("Address:"+person.getAddress());
  print("Phone:"+person.getPhone());
  print("Age:"+person.getAge().toString());
  print("EDUCATIONAL BACKGROUND");
  print("JHS:"+person.getJHS());
  print("SHS:"+person.getSHS());
  print("University:"+person.getUniversity());
}

class Person{
  //Fields - Data for the class comes here
   String firstname,lastname,address,phone,jhs,shs,university;
   int age;
   //Setter methods
  void setFirstName(String firstname){
    this.firstname = firstname;
  }
  void setLastName(String lastname){
    this.lastname = lastname;
  }
  void setAddress(String address){
    this.address = address;
  }
  void setPhone(String phone){
    this.phone = phone;
  }
  void setAge(int age){
    this.age = age;
  }
  void setJHS(String jhs){
    this.jhs = jhs;
  }
  void setSHS(String shs){
    this.shs = shs;
  }
  void setUniversity(String university){
    this.university = university;
  }
  //Getter methods
  String getFirstName(){
    return firstname;
  }
  String getLastName(){
    return lastname;
  }
  String getAddress(){
    return address;
  }
  String getPhone(){
    return phone;
  }
  int getAge(){
    return age;
  }
  String getJHS(){
    return jhs;
  }
  String getSHS(){
    return shs;
  }
  String getUniversity(){
    return university;
  }
}


The output will be:


PERSONAL INFORMATION

First Name:Godwin

Last Name:Ashong

Address:Mango street D44, Teshie - Accra, Ghana

Phone:+233203930303

Age:22

EDUCATIONAL BACKGROUND

JHS:Pre-vas Royal Kids

SHS:Teshie - Presec

University:KNUST


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


class child_class_name extends parent_class_name 


Note: Dart doesn’t support multiple inheritance.


Example


Let's create an Employee class which inherits the Person class. Then we can add new functions like Position and salary setter and getter methods.


void main() { 
   Employee person = new Employee();
   //Set the values
   person.setFirstName("Godwin");
  person.setLastName("Ashong");
  person.setAddress("Mango street D44, Teshie - Accra, Ghana");
  person.setPhone("+233203930303");
  person.setAge(22);
  person.setJHS("Pre-vas Royal Kids");
  person.setSHS("Teshie - Presec");
  person.setUniversity("KNUST");
  //Get the set values and print out the results
  print("PERSONAL INFORMATION");
  print("First Name:"+person.getFirstName());
  print("Last Name:"+person.getLastName());
  print("Address:"+person.getAddress());
  print("Phone:"+person.getPhone());
  print("Age:"+person.getAge().toString());
  print("EDUCATIONAL BACKGROUND");
  print("JHS:"+person.getJHS());
  print("SHS:"+person.getSHS());
  print("University:"+person.getUniversity());
  person.setPosition("Managing Director");
  person.setSalary(2500);
  print("Position:"+person.getPosition());
  print("Salary: Ghc "+person.getSalary().toString());
}

class Person{
  //Fields - Data for the class comes here
   String firstname,lastname,address,phone,jhs,shs,university;
   int age;
   //Setter methods
  void setFirstName(String firstname){
    this.firstname = firstname;
  }
  void setLastName(String lastname){
    this.lastname = lastname;
  }
  void setAddress(String address){
    this.address = address;
  }
  void setPhone(String phone){
    this.phone = phone;
  }
  void setAge(int age){
    this.age = age;
  }
  void setJHS(String jhs){
    this.jhs = jhs;
  }
  void setSHS(String shs){
    this.shs = shs;
  }
  void setUniversity(String university){
    this.university = university;
  }
  //Getter methods
  String getFirstName(){
    return firstname;
  }
  String getLastName(){
    return lastname;
  }
  String getAddress(){
    return address;
  }
  String getPhone(){
    return phone;
  }
  int getAge(){
    return age;
  }
  String getJHS(){
    return jhs;
  }
  String getSHS(){
    return shs;
  }
  String getUniversity(){
    return university;
  }
}
class Employee extends Person{
  String position;
  double salary;
  void setPosition(String position){
    this.position = position;
  }
  void setSalary(double salary){
    this.salary = salary;
  }
  String getPosition(){
    return position;
  }
  double getSalary(){
    return salary;
  }
}


Output


PERSONAL INFORMATION

First Name:Godwin

Last Name:Ashong

Address:Mango street D44, Teshie - Accra, Ghana

Phone:+233203930303

Age:22

EDUCATIONAL BACKGROUND

JHS:Pre-vas Royal Kids

SHS:Teshie - Presec

University:KNUST

Position:Managing Director

Salary: Ghc 2500


As you can see, the Employee class inherits all the methods of the Person class.


Types of Inheritance


Inheritance can be of the following three types −

Single − Every class can at the most extend from one parent class.

Multiple − A class can inherit from multiple classes. Dart doesn’t support multiple inheritance.

Multi-level − A class can inherit from another child class.


To illustrate Multi-level inheritance, we can create another class Teacher which inherits the Employee class. The Teacher class will therefore have all the methods the Employee class inherited from the Person class as well as the methods in only the Employee class.


The modified code is shown below:


void main() { 
   Teacher person = new Teacher();
   //Set the values
   person.setFirstName("Godwin");
  person.setLastName("Ashong");
  person.setAddress("Mango street D44, Teshie - Accra, Ghana");
  person.setPhone("+233203930303");
  person.setAge(22);
  person.setJHS("Pre-vas Royal Kids");
  person.setSHS("Teshie - Presec");
  person.setUniversity("KNUST");
  //Get the set values and print out the results
  print("PERSONAL INFORMATION");
  print("First Name:"+person.getFirstName());
  print("Last Name:"+person.getLastName());
  print("Address:"+person.getAddress());
  print("Phone:"+person.getPhone());
  print("Age:"+person.getAge().toString());
  print("EDUCATIONAL BACKGROUND");
  print("JHS:"+person.getJHS());
  print("SHS:"+person.getSHS());
  print("University:"+person.getUniversity());
  person.setPosition("Managing Director");
  person.setSalary(2500);
  print("Position:"+person.getPosition());
  print("Salary: Ghc "+person.getSalary().toString());
  person.setSubject("Mathematics");
  print("Subject Taught: "+person.getSubject());
}

class Person{
  //Fields - Data for the class comes here
   String firstname,lastname,address,phone,jhs,shs,university;
   int age;
   //Setter methods
  void setFirstName(String firstname){
    this.firstname = firstname;
  }
  void setLastName(String lastname){
    this.lastname = lastname;
  }
  void setAddress(String address){
    this.address = address;
  }
  void setPhone(String phone){
    this.phone = phone;
  }
  void setAge(int age){
    this.age = age;
  }
  void setJHS(String jhs){
    this.jhs = jhs;
  }
  void setSHS(String shs){
    this.shs = shs;
  }
  void setUniversity(String university){
    this.university = university;
  }
  //Getter methods
  String getFirstName(){
    return firstname;
  }
  String getLastName(){
    return lastname;
  }
  String getAddress(){
    return address;
  }
  String getPhone(){
    return phone;
  }
  int getAge(){
    return age;
  }
  String getJHS(){
    return jhs;
  }
  String getSHS(){
    return shs;
  }
  String getUniversity(){
    return university;
  }
}
class Employee extends Person{
  String position;
  double salary;
  void setPosition(String position){
    this.position = position;
  }
  void setSalary(double salary){
    this.salary = salary;
  }
  String getPosition(){
    return position;
  }
  double getSalary(){
    return salary;
  }
}
class Teacher extends Employee{
  String subject;
  void setSubject(String subject){
    this.subject = subject;
  }
  String getSubject(){
    return subject;
  }
}


The output


PERSONAL INFORMATION

First Name:Godwin

Last Name:Ashong

Address:Mango street D44, Teshie - Accra, Ghana

Phone:+233203930303

Age:22

EDUCATIONAL BACKGROUND

JHS:Pre-vas Royal Kids

SHS:Teshie - Presec

University:KNUST

Position:Managing Director

Salary: Ghc 2500

Subject Taught: Mathematics



Dart – Class Inheritance and Method Overriding


Method Overriding is a mechanism by which the child class redefines a method in its parent class. 


Syntax

@override

method and its implementation comes here


Let's say a teacher has a basic salary and in addition, bonus is calculated by multiplying the hours worked and the working rate.

That's salary = salary + hours*rate.

We can override the salary class in the Employee class by adding setters to set the hours and rate and use it in the calculation for a salary.


The modified code is shown below:


void main() { 
   Teacher person = new Teacher();
   //Set the values
   person.setFirstName("Godwin");
  person.setLastName("Ashong");
  person.setAddress("Mango street D44, Teshie - Accra, Ghana");
  person.setPhone("+233203930303");
  person.setAge(22);
  person.setJHS("Pre-vas Royal Kids");
  person.setSHS("Teshie - Presec");
  person.setUniversity("KNUST");
  //Get the set values and print out the results
  print("PERSONAL INFORMATION");
  print("First Name:"+person.getFirstName());
  print("Last Name:"+person.getLastName());
  print("Address:"+person.getAddress());
  print("Phone:"+person.getPhone());
  print("Age:"+person.getAge().toString());
  print("EDUCATIONAL BACKGROUND");
  print("JHS:"+person.getJHS());
  print("SHS:"+person.getSHS());
  print("University:"+person.getUniversity());
  person.setPosition("Managing Director");
  person.setHours(30);
  person.setRate(8.5);
  person.setSalary(2500);
  print("Position:"+person.getPosition());
  print("Salary: Ghc "+person.getSalary().toString());
  person.setSubject("Mathematics");
  print("Subject Taught: "+person.getSubject());
}

class Person{
  //Fields - Data for the class comes here
   String firstname,lastname,address,phone,jhs,shs,university;
   int age;
   //Setter methods
  void setFirstName(String firstname){
    this.firstname = firstname;
  }
  void setLastName(String lastname){
    this.lastname = lastname;
  }
  void setAddress(String address){
    this.address = address;
  }
  void setPhone(String phone){
    this.phone = phone;
  }
  void setAge(int age){
    this.age = age;
  }
  void setJHS(String jhs){
    this.jhs = jhs;
  }
  void setSHS(String shs){
    this.shs = shs;
  }
  void setUniversity(String university){
    this.university = university;
  }
  //Getter methods
  String getFirstName(){
    return firstname;
  }
  String getLastName(){
    return lastname;
  }
  String getAddress(){
    return address;
  }
  String getPhone(){
    return phone;
  }
  int getAge(){
    return age;
  }
  String getJHS(){
    return jhs;
  }
  String getSHS(){
    return shs;
  }
  String getUniversity(){
    return university;
  }
}
class Employee extends Person{
  String position;
  double salary;
  void setPosition(String position){
    this.position = position;
  }
  void setSalary(double salary){
    this.salary = salary;
  }
  String getPosition(){
    return position;
  }
  double getSalary(){
    return salary;
  }
}
class Teacher extends Employee{
  String subject;
  double hours;
  double rate;
  double salary;
  void setSubject(String subject){
    this.subject = subject;
  }
  String getSubject(){
    return subject;
  }
  void setHours(double hours){
    this.hours = hours;
  }
  double getHours(){
    return hours;
  }
  void setRate(double rate){
    this.rate = rate;
  }
  double getRate(){
    return rate;
  }
  
  @override 
  void setSalary(double salary){
    this.salary = salary + hours*rate;
  }
}


Output


PERSONAL INFORMATION

First Name:Godwin

Last Name:Ashong

Address:Mango street D44, Teshie - Accra, Ghana

Phone:+233203930303

Age:22

EDUCATIONAL BACKGROUND

JHS:Pre-vas Royal Kids

SHS:Teshie - Presec

University:KNUST

Position:Managing Director

Salary: Ghc 2755

Subject Taught: Mathematics


NOTE: You can only override a method implementation and not its arguments(parameters). For instance, you will get a syntax error if you try to override the setSalary argument as (double salary, double hours, double rate) since the parent argument is only (double salary). Thus you can't override the setSalary method as:


@override
void setSalary(double salary, double hours, double rate){
    this.salary = salary + hours*rate;
}


Now let's continue with the interface now that you've understood what class is.


In the following program, we are declaring a class Calculations. The PerformCalculations class implements the implicit interface declaration for the Calculations class. The main function creates an object of the PerformCalculations class using the new keyword. This object is used to invoke the functions a defined in the PerformCalculations class.


void main() { 
   PerformCalculations cal = new PerformCalculations();
   double a = 4, b=6;
   int c = 5,d=2;
   print("$a+$b = "+cal.sum(a,b).toString());
  print("$a-$b = "+cal.subtract(a,b).toString());
  print("$a/$b = "+cal.divide(a,b).toString());
  print("$a x $b = "+cal.multiply(a,b).toString());
  print("$c modulus $d = "+cal.modulus(c,d).toString());
}  
class Calculations{
  double sum(double a, double b){
    
  }
  double subtract(double a, double b){
    
  }
  double multiply(double a, double b){
    
  }
  double divide(double a, double b){
    
  }
  int modulus(int a, int b){
    
  }
}
class PerformCalculations implements Calculations{
  double sum(double a, double b){
    return a+b;
  }
  double subtract(double a, double b){
    return a-b;
  }
  double multiply(double a, double b){
    return a*b;
  }
  double divide(double a, double b){
    return a/b;
  }
  int modulus(int a, int b){
    return a%b;
  }
}


It should produce the following output −


4+6 = 10

4-6 = -2

4/6 = 0.6666666666666666

4 x 6 = 24

5 modulus 2 = 1


Implementing Multiple Interfaces


A class can implement multiple interfaces. The interfaces are separated by a comma. The syntax for the same is given below −

class identifier implements interface-1,interface_2,interface_4…….

To illustrate this, let's add a new interface and implement it in our PerformCalculations class.


Example


void main() { 
   PerformCalculations cal = new PerformCalculations();
   double a = 4, b=6;
   int c = 5,d=2;
   print("$a+$b = "+cal.sum(a,b).toString());
   print("$a-$b = "+cal.subtract(a,b).toString());
   print("$a/$b = "+cal.divide(a,b).toString());
   print("$a x $b = "+cal.multiply(a,b).toString());
   print("$c modulus $d = "+cal.modulus(c,d).toString());
   if(cal.isEven(c)){
     print("$c is even");
   }else{
     print("$c is odd");
   }
   cal.multiples(d);
}  
class Calculations{
  double sum(double a, double b){
    
  }
  double subtract(double a, double b){
    
  }
  double multiply(double a, double b){
    
  }
  double divide(double a, double b){
    
  }
  int modulus(int a, int b){
    
  }
}
class Maths{
  bool isEven(int a){
    
  }
  void multiples(int a){
    
  }
}
class PerformCalculations implements Calculations,Maths{
  double sum(double a, double b){
    return a+b;
  }
  double subtract(double a, double b){
    return a-b;
  }
  double multiply(double a, double b){
    return a*b;
  }
  double divide(double a, double b){
    return a/b;
  }
  int modulus(int a, int b){
    return a%b;
  }
  bool isEven(int a){
    if(a%2==0){
      return true;
    }else{
      return false;
    }
  }
  void multiples(int a){
    for(int i=1;i<=12;i++){
      print("$a x $i = ${a*i}");
    }
  }
}


Output


4+6 = 10

4-6 = -2

4/6 = 0.6666666666666666

4 x 6 = 24

5 modulus 2 = 1

5 is odd

2 x 1 = 2

2 x 2 = 4

2 x 3 = 6

2 x 4 = 8

2 x 5 = 10

2 x 6 = 12

2 x 7 = 14

2 x 8 = 16

2 x 9 = 18

2 x 10 = 20

2 x 11 = 22

2 x 12 = 24


PACKAGE


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.


We will elaborate more when we start developing our flutter applications.


Library


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: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.
2dart:core
Built-in types, collections, and other core functionality for every Dart program. This library is automatically imported.
3dart: math
Mathematical constants and functions, plus a random number generator.
4dart: convert
Encoders and decoders for converting between different data representations, including JSON and UTF-8.
5dart: typed_data
Lists that efficiently handle fixed sized data (for example, unsigned 8 byte integers).


Example


To call the square root function, we have to import the dart:math library so we could use the sqrt function.


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. (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


Async


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.


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 web server 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 web server 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 same folder as your dart file.


1.  Adjei

2.  Ama

3.  Adzovi

4. Fuseni


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("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. Adjei
2. Ama
3. Adzovi
4. Fuseni


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.


We will use the async more during the flutter development when we connect to the internet to fetch some data. We use the future to wait for the data and when it arrives, we process the data.

While waiting, the other blocks of code can still be executed.

SponsoredAdvertise