Categories
Dart

Dart Libraries

What is Dart Library ?

A Library in any programming language is a set of code which was pre-written by any developer so that others can use them in their own programs just by importing them in program.

Libraries are collection of functions, variables, typedefs, constructors, classes and many more concepts to develop some useful code reusable to any developers just by adding some reference points which is library imports.

Libraries are used to reuse the code so that people do not have to write the set of codes which are frequently used.

For ex :

Print() method is function written in dart:core library so that for displaying a data we don’t need to write that code every time. You just have to import specific library whose functions or classes you want to use.

What is Library Import ?

Importing a library makes that particular set of code(which may contain different functions, classes, variable and typedef etc.) which we want to use in our current program accessible to the user.

We can import multiple library at a time in the program.

Every programming languages have therir own set of predefined libraries which helps users to save their time and efficiency.

Dart also have some libraries which makes our coding more easier.Some of them are :

dart:core

Built-in types, collections, and other core functionality. This library is automatically imported into every Dart program.

dart:async

Support for asynchronous programming, with classes such as Future and Stream.

dart:math

Mathematical constants and functions, plus a random number generator.

dart:convert

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

dart:html

DOM and other APIs for browser-based apps.

dart:io

I/O for programs that can use the Dart VM, including Flutter apps, servers, and command-line scripts.

To import any library in the dart “import” keyword is used.

The only required argument to import any library is a URI(Uniform Resource Identifier- is the locator of the library resource in project) specifying the library.

For built-in libraries, URI syntax for importing library is as below :

// libraryName is the Name of the predefined dart library.
import ‘dart:libraryName’;

For custom libraries(which can be created by any random user), URI syntax for importing library is as below :

// where test/test.dart is URI of the custom library.
import ‘package:test/test.dart’;

For better experiencing the use of custom libraries create two dart files. Let say one is test.dart and other is PoliticiansTest.dart

create Test.dart file and copy below code in that file to test.

// so here to use PoliticiansTest class which is located inside the PoliticiansTest.dart file, we have to import that PoliticiansTest.dart library.
import 'package:DartSample/PoliticiansTest.dart';
void main(){
  PoliticiansTest politiciansTest=new PoliticiansTest();
  politiciansTest.politicianFromTheCountry("N. Modi", "India");
  politiciansTest.politicianFromTheCountry("B. Obama", "USA");
  politiciansTest.politicianFromTheCountry("N. Mandela", "Africa");
}
-Create PoliticiansTest.dart file and copy below code in that file to test. 
class PoliticiansTest{
  politicianFromTheCountry(String name,String country){
    print("$name is politician from the country $country");
  }
}

Output :

N. Modi is politician from the country India
B. Obama is politician from the country USA
N. Mandela is politician from the country Africa

Similarly, you can also provide prefix for libraries to simplify the library import or distniguish the component when there are two libraries having same method or class etc.

as keyword is used for providing prefix to the library imported.

Create Library1.dart file and copy below code in that file to test.

testLibrary(){
print(“Testing Library First”);
}

Create Library2.dart file and copy below code in that file to test.

testLibrary(){
print(“Testing Library Second”);
}

Create test.dart file and copy below code in that file to test.

// prefixing lib1.dart with lib2 using as keyword
import 'package:DartSample/Library1.dart' as lib1;
import 'package:DartSample/Library2.dart' as lib2;
void main(){
	lib1.testLibrary();
	lib2.testLibrary();
}

Output :

Testing Library First
Testing Library Second

By prefixing any library we can access class , variables and methods with prefix. In above example, we have added prefix to the library1.dart as lib1. Now we can access any class, variables and methods from the library1.dart using that prefix like testLibrary() method from the library.

Therefore Library is a great way for code reusability in any manner to improve the programming efficiency. Hence, results in greater productivity.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Generics

In dart programming, all the collections(for ex: list,map, set etc.) are heterogeneous nature by default.

heterogeneous nature means collections can have values of different data types.

For ex :

void main(){
// this heterogeneous list is not defined with specific type. So we can add values of any data type like String, int, boolean etc.
	var list=List();
	list.add("red");
	list.add(1);
	list.add(true);
}

We can also have homogeneous collections by defining specific type for the collection.

Homogeneous collection means it can have the values of same data type we have specified while declaring the collection.

For ex :

void main(){
// this list is defined with specific data type “String”. So we can’t add values other than String data types.
	var list=List<String>();
	list.add("red");
	list.add(“green);
	list.add(“blue);
}

Heterogeneous Structure(either it is collections, methhods etc.) can be used when you just want to store values of any data type. While, homogeneous collections are used for storing , retriving and manipulating the data of the same type. it’s very tough for hetrogeneous structures to manipulate the data easily. As they can be of any data type.

For ex :

void main(){
	var list=List();
	list.add("red");
	list.add("green");
// value is of int type
	list.add(1);
	
	for(int i=0;i<list.length;i++){
		//we’ll get an error when i equals to 2 as the value at the index 2 is not of the 		String data type.
    		String value=list[i];
		print(value);
	} 
}

Above example, can be solved either storing the each value of list to the variable of that particular data type or type casting while retrieving data. Which is not a proper solution.

A better solution is to use homogeneous collection or methods instead.

Generics are also used for achieving the same i.e.,we are manipulating and storing the values of the same data type. Which is also known as type safety.

What is generics ?

Generics are used to ensure that the Objects or functions we manipulate are of the same data type or say type safe to use.

we can’t hold objects of different types while using generics as it follows type safety.

Generics Syntax :

// here className can be any type of object i.e., String, List, Map or your custom class etc.

// And DataType is the type specified for the values that can be stored in that particular
data structure(here, className is that data structure).

className variableName=new className()

Generics will give you the error at compile time if you store the values other than specified data type.

Let’s take an example to understand the Generics briefly.

For ex :

void main() {
// this generic map is defined with key of int data type and value of String data type.
  var map=Map<int,String>();
  map[1]="Red";
  map[2]="Green";
  map[3]="Blue";
  map.forEach((k,v)=>print(v));
}

Output :

Red
Green
Blue

This way you don’t need any type casting or worry about any unknow data type conversion errors while you use generic structures.

What is generic Method ?

A generic method is a method that is declared with the type parameters.

Let’s take an example of generic method.

For ex :

void main(){
  int rank = 1;
  double number = 0.5;
  String value = "test";
  print("Integer Value : ");
  getDisplayValue(rank);

  print("Double Value : ");
  getDisplayValue(number);

  print("String Value : ");
  getDisplayValue(value);
}

//to make a function generic we add <T> after the name of the function. <T> stands for the type of the class like String or int or List etc. The compiler will cast the passed parameter to the appropriate base class object and let the function accept that type parameter.
getDisplayValue<T>(T result) {
    print(result);
}

Output :

Integer Value :
1
Double Value :
0.5
String Value :
test

Above function: getDisplayValue(T result) can also be replaced as below function. Object is the parent class of each class. So whatever type of parameter will you pass will be converted to the type of base class Object. So, there will be no compile time or runtime error as it is casted properly to the base class.

getDisplayValue(Object result) {
print(result);
}

In above example, we have created a generic method of Type T which can accept the parameter of type T. Here adding means that the arguments passed to the method is of Type T and is acceptable as they are also converted to the appropriate base class.

Practice this concept more and more to understand this complex and critical concept. Generics will be very helpful to achieve code reusability and code efficiency while developing bigger projects.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Async

To understand the dart async, you must understand the type of execution flow.

There are 2 types in which the task or program can be executed.

  1. Synchronous Execution
  2. Asynchronous Execution(Async)

What is Synchronous Execution?

In general, every program you write works in a synchronous fashion.

Synchronous execution means the execution of program will work evaluating the values statement by statement(code instruction).

Synchronous Execution means the execution of program doesn’t move to the next expression until the current expression, function or block of code gets evaluated(executed).

Synchronous operation gets executed always on the main thread(A thread is a unit of program execution to evaluate or execute the block of code or program).

Each program has at least one thread to process its task or say program which is main thread.

For ex :

void main(){
	tuition();
	getDataFromServer();
	print(“End”);
}
void tuition(){
	print(“Dart Classes Ongoing”);
}
getDataFromServer(){
	//Heavy Calculation which takes around 5 seconds to execute
}

In above example, execution starts with tuition function(i.e., executes each statements or code written in the tuition). After that it evaluates the getDataFromServer() function which takes around 5 seconds to execute. Till then the Main thread gets blocked as our execution flow can’t move further to the next instruction print(“End”) until current statement or function gets evaluated completely.

This Execution will not be useful when you want to make UI changes to your application or you want to continue your execution to next statement when current statement requires heavy calculation in the program. So, to overcome this situation the concept of asynchronous execution was introduced.

What is Asynchronous Execution ?

In general, your UI runs on a single thread to interact with user which is known as main thread. Therefore all code will run on main thread which might result in poor performance due to heavy calculations or consuming operations. Till the execution of those heavy operations your UI(i.e., main thread) is blocked. So, to run those heavy operations without blocking main thread or UI asynchronous execution comes to the rescue.

Let’s understand dart async with one of the useful concept known as then keyword.

What is then ?

As the name suggests, then keyword is used to wait for the asynchronous operation to complete written in particular function. After that then block gets executed which have the Future return type retrieved from that particular function.

Let’s take an example to briefly understand async operation using then keyword.

import 'dart:io';
void main() {
// then keyword is used to perform the calculation after particular async function gets executed completely. It must have a Future return type while using with then keyword for an async function. Here, readNews() returns the Future return type String to then block.
  readNews().then((String news){
    print(news);
  });
}
// readNews() is an async function having return type of String which will be evaluated after some time in future.
Future<String> readNews() async{
  print("War Started Today !!");
  sleep(const Duration(seconds:5));
  return "War Ended !!";
}

Output :

War Started Today !!
War Ended !!

In above example, first async function readNews() gets called. After the function completion then block associated with readNews() gets called which requires the return type passed by readNews function(here, String data type).

So, we can use then keyword with async function for asynchronous operations. Await is another alternative for then block to perform smoother asynchronous operations.

What is await ?

In dart async, await is used to wait for the execution of the function completes. await keyword is prefixed before the async function call. Await keyword can only be used in async functions as well as it’s always prefixed before the async functions to wait till that async function gets executed.

So to perform async function we need to declare main function as async function. To define any function as async we need to postfix the async keyword after the function-brackets().

Let’s take an example to briefly understand async operation using await keyword.

import 'dart:io';
games() async {
  // sleep method is useful to sleep your thread for specific time duration mentioned.
  sleep(const Duration(seconds:5));
  return "Playing PUBG";
}
main() async {
  print("Playing Clash Of Clans");
//await is prefixed before the async function games
  var test= await games();
  print(test);
}

Output :

Playing Clash Of Clans
Playing PUBG

In above example, program execution waits till the games() method gets executed and after that print statement is evaluated.

so, here async operation is used as the program execution will not move forward till the async function games() doesn’t get evaluated as we have used await function. Which will wait for the current function to get executed first and then move for further execution.

this process doen’t blocking main thread to execute any operation. But, we are just waiting for the games() function to be executed which is executing on the another thread.

Let’s take another async example scenario.

Future<void> getGameDetails() async {
  var newsDigest = await gameReports();
  print(newsDigest);
}
main() {
  getGameDetails();
  playingChess();
  playingCricket();
  playingCOC();
}
playingChess() {
  print("Playing Chess now-a-days");
}
playingCricket() {
  print("Playing Cricket now-a-days");
}
playingCOC() {
  print("Playing Clash of clans now-a-days");
}
const game = 'Playing PUBG now-a-days';
const duration = Duration(seconds: 5);

// here Future<String> means the Return type of the function is String but function will be completed in future. 
Future<String> gameReports() =>Future.delayed(duration, () => game);

Output :

Playing Chess now-a-days
Playing Cricket now-a-days
Playing Clash of clans now-a-days
Playing PUBG now-a-days

In above example, first we have called async function getGameDetails(). As it is an async task it will be executing on the separate thread. After that we have called three functions playingChess(), playingCricket() and playingCOC(). They all gets executed synchronously as they are executing on main thread. The output of the aync function getGameDetails() is printed at last because that asyc method takes around 5 seconds to execute. Before that all methods gets executed so their outputs or evaluations are printed before it.

Future API represents the result of the async functions which will be processed or completed later.

When a function returns the data type with future , two things happen

  1. the function will be queued up for the execution and returns an uncompleted Future object.
  2. when the execution is finished, the future object returns with value or an error.

In above example, gameReports() method which is more complex as well as slow is queud up for the execution first and then at the end of the execution it returns the future object with string type value.

So, in this way we can perform heavy calculations without blocking main thread or UI of the program and provide smoother experience to user.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Typedef

In dart, Typedef is a keyword used to declare alias or reference to the function in the program. With the help of this alias or reference we can call different functions having same signature(i.e., having same number of parameters with same data types). For typedef, return type does not considered as part of the function signature.

In short, typedef is used to call(refer) the different functions having the same signature assigned to typedef for smoother function manipulation.

Syntax :

// Here, parameterList stands for different types of parameters required in function.
typedef variableName(parameterList);

For ex :

// here,  SportLegends is the typedef variable which can be assigned to the different functions having same signature as declared with typedef.
typedef SportLegends(String Player1,String Player2);

// Tennis function have same signature(i.e., both String type parameters) as typedef SportLegends().
Tennis(String Player1, String Player2){
  print("$Player1 and $Player2 are two great players of tennis.");
}

// Cricket function have same signature(i.e., both String type parameters) as typedef SportLegends().
Cricket(String Player1,String Player2){
  print("$Player1 and $Player2 are two great players of Cricket.");
}

// Cricket function have same signature(i.e., both String type parameters) as typedef SportLegends().
Football(String Player1,String Player2){
  print("$Player1 and $Player2 are two great players of Football.");
}

void main(){
  SportLegends legends;
  // assigning typedef to reference the Tennis function having the same signature as typedef  SportLegends.
  legends=Tennis;
  legends("Roger Federer","Rafael Nadal");
  legends=Cricket;
  legends("Sachin Tendulkar","AB De Villiars");
  legends=Football;
  legends("Cristiano Ronaldo","Lionel Messi");
}

Output :

Roger Federer and Rafael Nadal are two great players of tennis.
Sachin Tendulkar and AB De Villiars are two great players of Cricket.
Cristiano Ronaldo and Lionel Messi are two great players of Football.

Hence, typedef becomes really useful to point-out different functions having same signature with single variable to reduce boiler-plate coding.

It can be useful to learn typedef as it makes your work very handy to map different functions with single variable as per your requirements.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Advanced Functions

Dart functions don’t need classes for writing different functions. Which means dart treats functions as first class objects.

Dart supports advance level functions like lambda functions.

Lambda functions are a concise and efficient mechanism to represent functions with lesser code and better performance.

Syntax of Lamda :

returnType functionName(arguments) => expressions;

For ex :

game(){

/* here return type will be decided at runtime based on the value return from the function. In this case we are returning 100 so, the return type of function game is int type.*/

return 100;

}

// above code can be written as,
game()=>100;

I think this is amazing because Lambda function removes boiler plate code from your programming and optimize your work efficiency.

Lambda function with parameters

parameters passed in lambda functions do not need to specify the data type. The data type of the parameter will be interpreted based on the value passed.

For ex :

game(gameName,rank)=>"rank $rank game of the world is $gameName";
void main(){
  print(game("Minecraft",1));
}

in above example, we didn’t declare the data type for arguments. As It is optional to pass parameters for the lambda functions in dart.

In above example, gameName variable will be assigned to String data type as the value passed to parameter is “Minecraft” which is of String type.

This way lambda functions are useful for reducing the code as well as provding simplified syntax structure.

Optional parameters

Yes, dart supports optional parameters in the functions.

Optional parameters are the parameters which are not necessary to pass in the function call.

Optional parameters can have default values (if any values are not passed for optional parameters the optional parameter will have that default value we have provide in the function definition signature).

Optional parameters can be declared only after the required parameters.

There are two types of optional parameters

  1. Positional parameters
  2. Named parameters

Positional Parameters

Positional parameters are the type of optional parameters which are included inside square brackets – [ ] .

In any function, if you have declared more than one positional parameters then you have to pass them in the same order as you have defined in the function signature.

For ex :

void main(){
		// order of passing parameters is important in function call with positional parameters.
		watchMovies("An Action Movie","Star wars", 1999);
		watchMovies("An Action Movie","Terminator");
}

// watchMovies() has default int positional parameter year with value 1984. Any function call to watchMovies function without positional parameter year will be assigned default value 1984.
watchMovies(String category, [String movie, int year = 1984]){
  print(movie + " was $category released in "+ year.toString());
}

Output :

Star wars was An Action Movie released in 1999
Terminator was An Action Movie released in 1984

Named Parameters

Named parameters are the type of optional parameters which are included inside curly brackets – { } .

Named parameters are the parameters which can be passed in function call with the name we have used for that particular parameter in the function signature.

To pass named parameters in function call, you must have to use parameter name defined in the function signature.

Function calling with named parameter will be look like below,

// Here, parameterName is the name defined in function. ParameterValue will be assigned to that parameterName.
function call(parameterName : parameterValue);

For ex :

void main(){
  // Here, year and series are named parameters which are defined in the method signature of watchSeries().
 watchSeries("A Drama Series",year: 2011, series: "Game of Thrones");
}

// Any function call to watchSeries() function without named parameter year will be assigned default value 3000.
watchSeries(String category, {series, year=3000}){
  print(series + " was $category released in "+ year.toString());
}

Output :

Game of Thrones was A Drama Series released in 2011
The Walking Dead was A Drama Series released in 2010

In named parameters, you can change the order of passing the optional parameters in function calling as we did in above example.

These are some of the advance approaches available in dart functions to make your programs smoother and easy to code.

Also, dart programs can run with only functions without use of class-object structure.

This shows that how much vital role functions play in dart language. So, mastering functions in dart will help your large projects more redable.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Access Modifiers

Access modifiers or access specifiers (i.e, private, public and protected) are not supported in dart language.

Although to make any class or method private(i.e., access of that specific class or method to have scope limited to themselves only.) you have to start the function or class name using _.

For ex :

//_Test is a private class as we have defined it using _
class _Test{
//_Hello() is a private method as we have defined it using _
	_Hello(){
	}
}

Any Class or methods written in program are by default private in dart.

So there is no concept of access specifiers in dart language.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Exception Handling

Exception in a programming language is a termination of the program during execution.

Exception is an unwanted or unexpected event which interrupts the normal flow of the program execution.

Exception must be taken care to continue our program execution. Otherwise program or application gets terminated.

For ex :

void main(){
  	List games=new List();
	print("Exception Test");
	// Index out of range exception will occur due to no element will be found in the list at index as list is empty. Hence, further statements will not executed with the termination of the program.
  	print(games[5]);
	print("Exception Test");
}

Whenever an exception occurs, program gets terminated abnormally without executing remaining part of the program. That’s why we have to handle the exception.

What is Exception Handling?

Exception handling is a mechanism to solve or handle the runtime errors. There are different kinds of exceptions can strike based on which type of mistake you have made while writing your program. Like, IndexOutOfRangeException, IOException, NullPointerException etc.

Exception handling is the mechanism to handle unknown mistakes you made in your program to prevent program or application termination.

Dart have some concepts for handling exceptions smoothly as following,

  • try
  • on/catch
  • finally
  • throw

try

Block of code or statements which might result in an exception must be kept inside try block to throw generated exception.

Generated exception will be thrown to the on or catch block.

Syntax :

try{
            // block of code
}catch(e){
            // handle thrown exception
}

Try block must be followed by on or catch or finally block.

on/catch

On or catch block are used to handle the thrown exception from try block.

On or catch keywords can be used separately as well as together to catch an exception.

A try block can be followed by multiple catch blocks. Multiple catch blocks are used to handle different types of exceptions.

Syntax :

try{
            // code block
}
// to use on keyword it must be followed by the Exception that may occur. On should be used only when you definitely know that particular exception will occur from try block. Otherwise, catch will always handle your exceptions smoothly.
on ExceptionName catch(e){
            // code block
}

In above syntax, ExceptionName is the type of exception that may occur based on different situations. Like, ArithmaticException, IntegerDivisionByZeroException etc. can be thrown via try block if you made some mistake related to them.

finally

finally is a block used to perform certain operations whether exceptions take place in program or not.

finally is generally used to release the different resources requested during the operation. In general case, releasing database resources, closing opened files etc.

Syntax :

try{

}finally{
            //statements you want to perform
}

finally must have an associate try block.

For ex :

void main(){  
  try{
     List<String> games=new List();
    print(games[5]);
  }on IntegerDivisionByZeroException catch(e){
    print("Divide By Zero Error");
  }on IndexError catch(e){
    print("Handle Index Error");
  }finally{
    print("Release Resources.");
  }
}

Output :

Handle Index Error
Release Resources.

Throw

Throw keyword is used to manually throw the exception in programs.

Generally, it is used to terminate the program while some logical condition does not satisfies as per our requirement.

Syntax :

throw new ExceptionName();

Here ExceptionName is the exception you want to be thrown to terminate the program.

To solve the program termination due to exceptions thrown using throw keyword, use throw in try-catch block.

For ex :

void main(){
  int x=5,y=0;
  if(y==0){
	// throwing an exception
     throw new IntegerDivisionByZeroException();
  }else{
    print(x);
  } 
}

Output :

Uncaught exception: IntegerDivisionByZeroException

Mistakes can happen by any one. So exception can strike at any point in your program and the solution of our problem is exception handling. Hence, we have learned exceptions to take care our programs for better user experience.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Interface

Generally, dart interface is used for as a replacement for multiple inheritance.

In dart, interface has the similar structure as class. Interface in dart defined using class keyword.

So, you will think that how an interface is different than class in dart?

Actually, interface in dart has been removed and the concept of interface in dart is optional(like no significance meaning in dart).

In dart, all classes are implicit interfaces which means classes itself act as interface.

Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements. If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.

In dart, An interface is a class which can be inherited by another class using implements keyword.

Methods inside interface should have body in dart language.

Any class which implements the interface must have to implement all the methods of that particular interface.

For ex :

class ButtonClickListener{
	void onButtonClick(){
    print("Default Button Clicked !!");	
  }
}
class Login implements  ButtonClickListener{
// implement all the methods of  ButtonClickListener
	onButtonClick(){
		print("Login Button Clicked !!");	
	}
}
class Signup implements  ButtonClickListener{
// implement all the methods of  ButtonClickListener
  onButtonClick(){
		print("Signup Button Clicked !!");	
	}
}
void main(){
// you can create an object of a class which act as implicit interface
  ButtonClickListener listener=new ButtonClickListener();
  listener.onButtonClick();
  Login login=new Login();
  login.onButtonClick();
  Signup signup=new Signup();
  signup.onButtonClick();
}

Output :

Default Button Clicked !!
Login Button Clicked !!
Signup Button Clicked !!

As dart is an optionally typed language, we don’t need to use interfaces. Just by writing appropriate methods with proper signature in classes is enough to fulfill your requirements.

Personally, i don’t suggest to focus interface in dart labguage as they do not have special case in dart language.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Collection

Collections are the data structures(i.e., specialised format for storing and managing diffrent types of data) which are used to store and manipulate the group of obects.

general collections supported by dart are as below,

  • List
  • Map
  • Set

out of which list and map have been already covered in previous tutorials.

What is Set ?

Dart Set is a collection of unique objects or items.

Dart set is an unordered collection as it not allows you to add elements or items at particular index or position in the set.

So, traversing to different position or elements in set is difficult.

If you try to add any item in the set which is already present then it will not be inserted or stored in the set. Which means set doesn’t allow the duplicate entries while inserting.

Set Common Properties

For ex :

void main(){  
  Set languages=new Set<String>();
  languages.add("C");
  languages.add("C++");
  languages.add("Java");
  languages.add("Dart");
  languages.add("C++");
  languages.add("Java");
  
  Set humanLanguage=new Set<String>();
  humanLanguage.add("English");
  humanLanguage.add("Hindi");
  humanLanguage.add("Gujarati");
  humanLanguage.add("C++");
  humanLanguage.add("Java");
  
  //duplicate values not allowed in set
  print(languages.toSet());
  print(languages.toList());
  print(languages.length);
  
  print(humanLanguage.length);
  print(humanLanguage.toSet());
  
  print(humanLanguage.contains("English"));
  print(humanLanguage.remove("Hindi"));
  print(humanLanguage.union(languages));
  print(humanLanguage.intersection(languages));
  print(humanLanguage.difference(languages));
  humanLanguage.clear();
  print(humanLanguage.length);
}

Output :

{C, C++, Java, Dart}
[C, C++, Java, Dart]
4
5
{English, Hindi, Gujarati, C++, Java}
true
true
{English, Gujarati, C++, Java, C, Dart}
{C++, Java}
{English, Gujarati}
0

Set collection have many methods which makes your collection handy to use.

Set is generally used to make your collection having unique values of same data type.

Make yourself comfortable with collections like List, Map and Set to better understand the different data structures.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Abstraction

Abstraction is the process of providing the functionality or essential requirements and hiding the implementation details from users to reduce the complexity and effort.

The best real life example of Abstraction is ATM Machine. We perform many transaction operations in ATM Machine like money transfer, withdrawal, balance check etc. But, we doesn’t know the internal functionality of the ATM while we perform our different ATM transactions.

Abstraction in Dart can be achieved using Abstract Class.

before learning about abstract class it’s better to have a look at abstract methods.

Abstract Method

Methods declared without implementation and ends with semicolon are known as abstract methods.

They can be declared inside Abstract class only.

Any abstract methods declared inside particular class must be implemented or say overriden by the class which inherits that particular class.

Abstract Class

Abstract class must be declared using Abstract keyword.

They are useless until any concrete class (the class which is not abstract) inherits it.

If a class inherits the Abstract class then either it must implement all the methods of that abstract class or must be declared as abstract class.

Abstract class can have abstract methods as well as concrete methods(non-abstract methods).

Abstract class can not be instantiated as it may have abstract methods.

As abstract methods have no body. So, accessing abstract methods is useless as it isn’t have any implementation.

That’s why Abstract class is also refered as Incomplete class.

For ex :

If a car has not proper brakes working. Nobody will drive that unsafe and incomplete car to avoid accidents.

Similarly, Abstract keyword ensures that no one would be allowed to instantiate the instance of an Abstract class(incomplete class). Even if an Abstract class have only non-abstract methods.

Let’s understand the Abstraction with a more common Example .

Let say we want to create a program for the Animal Feed.

For Animal Feed program, we will need feedAnimal() method for each Animal.

So, it’s a better way to create an abstract method in an Abstract class. By making this method abstract we ensures that each class has a feed method.

For ex :

abstract class Animal {

// Abstract method feedback() with no body and ends with semicolon
  feedAnimal();

  sleepAnimal(){
    print("Sleeping...");
  }
}
class Cat extends Animal {
	feedAnimal(){
    print("Feed Cat") ;
  }
}
class Dog extends Animal {
	feedAnimal(){
    print("Feed Dog") ;
  }
}
class Fox extends Animal {
	feedAnimal(){
    print("Feed Fox") ;
  }
}
void main(){
	Animal c=new Cat();
	Animal d=new Dog();
	Animal f =new Fox();
	c.feedAnimal();
	d.feedAnimal();
	f.feedAnimal();
}

Output :

Feed Cat
Feed Dog
Feed Fox

For this program, we have created a super abstract class Animal with abstract method feedAnimal().

Now, each subclass of Animal class must have to implement the abstract method feedAnimal() of the Abstract class Animal.

This way we ensure that all the classes who are the subclasses of the Animal class must have the feedAnimal() method.

So Abstraction is defining characteristics for Animal class that each Animal must be feeded. How each Animal is feeded is implemented in the classes which inherits Animal class and hidden from the user.

So, Abstraction is the process of showing the essential details and hiding internal implementation process.

You can have upper hand on Abstraction by practicing it more and more.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.