Data Types
Data types help you to categorize all the different types of data you use in your code. For e.g. numbers, texts, symbols, etc. The data type specifies what type of value will be stored by the variable. Each variable has its data type. Dart supports the following built-in data types :
Numbers
Strings
Booleans
Lists
Maps
Sets
Runes
Null
Var Keyword In Dart
In Dart, var automatically finds a data type. In simple terms, var says if you don’t want to specify a data type, I will find a data type for you.
void main(){
var name = "John Doe"; // String
var age = 20; // int
print(name);
print(age);
}
Built-In Types
In Dart language, there is the type of values that can be represented and manipulated. The data type classification is as given below:
Data Type	Keyword	Description
Numbers	int, double, num	It represents numeric values
Strings	String	It represents a sequence of characters
Booleans	bool	It represents Boolean values true and false
Lists	List	It is an ordered group of items
Maps	Map	It represents a set of values as key-value pairs
Sets	Set	It is an unordered list of unique values of same types
Runes	runes	It represents Unicode values of String
Null	null	It represents null value
When you need to store numeric value on dart, you can use either int or double. Both int and double are subtypes of num. You can use num to store both int or double value.
void main() {
// Declaring Variables  
int num1 = 100; // without decimal point.
double num2 = 130.2; // with decimal point.
num num3 = 50;
num  num4 = 50.4;  
// For Sum   
num sum = num1 + num2 + num3 + num4;
   
// Printing Info   
print("Num 1 is $num1");
print("Num 2 is $num2");  
print("Num 3 is $num3");  
print("Num 4 is $num4");  
print("Sum is $sum");  
   
}
Round Double Value To 2 Decimal Places
The .toStringAsFixed(2) is used to round the double value upto 2 decimal places in dart. You can round to any decimal places by entering numbers like 2, 3, 4, etc.
void main() {
// Declaring Variables
double price = 1130.2232323233233; // valid.
print(price.toStringAsFixed(2));
}
String
String helps you to store text data. You can store values like I love dart, New York 2140 in String. You can use single or double quotes to store string in dart.
void main() {
// Declaring Values     
String schoolName = "Diamond School";
String address = "New York 2140";   
// Printing Values
print("School name is $schoolName and address is $address");   
}
Create A Multi-Line String In Dart
If you want to create a multi-line String in dart, then you can use triple quotes with either single or double quotation marks.
void main() {
// Multi Line Using Single Quotes   
String multiLineText = '''
This is Multi Line Text
with 3 single quote
I am also writing here.
''';
   
// Multi Line Using D
String otherMultiLineText = """
This is Multi Line Text
with 3 double quote
I am also writing here.
""";
   
// Printing Information   
print("Multiline text is $multiLineText");
print("Other multiline text is $otherMultiLineText");
}
Type Conversion In Dart
In dart, type conversion allows you to convert one data type to another type. For e.g. to convert String to int, int to String or String to bool, etc.
Convert String To Int In Dart
You can convert String to int using int.parse() method. The method takes String as an argument and converts it into an integer.
void main() {
String strvalue = "1";
print("Type of strvalue is ${strvalue.runtimeType}");   
int intvalue = int.parse(strvalue);
print("Value of intvalue is $intvalue");
// this will print data type
print("Type of intvalue is ${intvalue.runtimeType}");
}
Convert String To Double In Dart
You can convert String to double using double.parse() method. The method takes String as an argument and converts it into a double.
void main() {
String strvalue = "1.1";
print("Type of strvalue is ${strvalue.runtimeType}");
double doublevalue = double.parse(strvalue);
print("Value of doublevalue is $doublevalue");
// this will print data type
print("Type of doublevalue is ${doublevalue.runtimeType}");
}
Convert Int To String In Dart
You can convert int to String using the toString() method. Here is example:
void main() {
int one = 1;
print("Type of one is ${one.runtimeType}");
String oneInString = one.toString(); 
print("Value of oneInString is $oneInString");
// this will print data type
print("Type of oneInString is ${oneInString.runtimeType}");
}
Convert Double To Int In Dart
You can convert double to int using the toInt() method.
void main() { 
   double num1 = 10.01;
   int num2 = num1.toInt(); // converting double to int
  print("The value of num1 is $num1. Its type is ${num1.runtimeType}");
  print("The value of num2 is $num2. Its type is ${num2.runtimeType}");
}
Booleans
In Dart, boolean holds either true or false value. You can write the bool keyword to define the boolean data type. You can use boolean if the answer is true or false. Consider the answer to the following questions:
Are you married?
Is the door open?
Does a cat fly?
Is the traffic light green?
Are you older than your father?
void main() {
bool isMarried = true;
print("Married Status: $isMarried");
}
Lists
The list holds multiple values in a single variable. It is also called arrays. If you want to store multiple values without creating multiple variables, you can use a list.
void main() {
List<String> names = ["Raj", "John", "Max"];
print("Value of names is $names");
print("Value of names[0] is ${names[0]}"); // index 0
print("Value of names[1] is ${names[1]}"); // index 1
print("Value of names[2] is ${names[2]}"); // index 2
  // Finding Length of List 
int length = names.length;  
print("The Length of names is $length");
}
Sets
An unordered collection of unique items is called set in dart. You can store unique data in sets.
 Info
Note: Set doesn’t print duplicate items.
void main() {
Set<String> weekday = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
print(weekday);
}
Maps
In Dart, a map is an object where you can store data in key-value pairs. Each key occurs only once, but you can use same value multiple times.
void main() {
Map<String, String> myDetails = {
   'name': 'John Doe',
   'address': 'USA',
   'fathername': 'Soe Doe'
};
// displaying the output
print(myDetails['name']);
}
Operators
It is used to perform an operation using set
 of operand(variable,constant,literals).
Operator access by symbol but define as a predefine method.
Dart supports the operators shown in the following table.
| Description | Operator | Associativity | 
|---|
| unary postfix: 
 
 | expr++expr--()[]?[].?.! | None | 
| unary prefix | -expr!expr~expr++expr--exprawaitexpr | None | 
| multiplicative | */%~/ | Left | 
| additive | +- | Left | 
| shift | <<>>>>> | Left | 
| bitwise AND | & | Left | 
| bitwise XOR | ^ | Left | 
| bitwise OR | | | Left | 
| relational and type test | >=><=<asisis! | None | 
| equality | ==!= | None | 
| logical AND | && | Left | 
| logical OR | || | Left | 
| if-null | ?? | Left | 
| conditional | expr1?expr2:expr3 | Right | 
| cascade | ..?.. | Left | 
| assignment | =*=/=+=-=&=^=etc. | Right | 
| spread (See note) | ......? | None | 
1)Unary:
This operator work, based on single operand.
1.1)  Post Increment | Decrement:
     first perform other operation (assignment, addition, print, memory allocation) then 
     increase or decrease value.
     var a=10;
     a++;
     a--;
1.2)   Pre Increment |  Decrement:
     first increase or decrease value then perform other operation 
      (assignment, addition, print, memory allocation)
     var a=5;
     ++a;
     --a; 
1.3)  unary minus: convert +ve value to -ve value
                  var a=10;
                  print(-a)
1.4)  tild  expression:  increase by one and apply minus symbol:
                   var c=50;
                   print(~c);
2) Binary Operator:  This operator uses minimum two operand to perform operation.
2.1)  Arithmetic:  It is used to perform operation using operand.
      +    add
      -    substract
      *    multiplication
      /    division
      ~/   divide return only integer part
2.2) Relational:  it is to apply condition under expression
                  <  less than
                  >  greater than
                  <= less than equal to
                  >= greater than equal to
2.3)  Comparison: it is used to compare data
                  ==   compare value  if equal then return true
                  !=   compare value if not equal then return true
2.4)  Assignment:  it is used to assign the value under variable, constant into memory
              
                   Simple Assignment   =
                   Complex Assignment  +=, -=,*=,/=,~/=
2.5)  Logical Operator: It is used to return true and false to group of condition .
                     &&  (and operator)  if all condition true then return true
                     ||   (or operator)  if any condition true then return true
                     !   (Not Operator) it convert true condition to false condition
2.6)  Bitwise operator:  it is used to perform binary shift & binary operation
                    & it multiply binary digit
                    !  it add binary digit
                    >> right shift operator
                    << left shift operator
                    ^  XOR 
3) Ternary Operator or Conditional statement:
It is used to solve condition based program under single line statement.
expression? true:false
Write a program to check even | odd?
void main()
{
    int a=11;
    String res = a%2==0?"Even":"Odd";
    print(res);
}
Write a program to check greater Age of Two Person?
void main()
{
    int Age1=40;
    int Age2=30;
    String res=Age1>Age2?"Age1 is greater":"Age2 is greater";
    print(res);
}
Conditional Statement in Dart:
It provide separate block level statement for true condition and false condition.
1) Simple If:
It will execute when condition is true.
Syntax
if(condition)
{
     Statement;
}
Write a program to apply grace mark if student is eligible for grace 
otherwise display normal mark?
e.g if mark is 28 then output "Total Mark is  33 and grace marks is 5"
void main()
{
    int marks = 30;
    if(marks>=28 && marks<33)
    {
        int g = 33-marks;
        marks = marks + g;
        print("Grace marks added ${g}");
    }
    print("Total Marks  ${marks}");
}
2) If--Else:
It will work when condition is true and false both.
if(condition)
{
      Statement;
}
else
{
      Statement;
}
3) Nested If--Else:
It is used to solve more than one condition based program.
if(condition)
{
     if(condition)
     {
     }
     else
     {
    }
}
else
{
    if(condition)
     {
     }
     else
     {
    }
}
{
        if(age1>age3)
        {
            print("Age1 is greater");
        }
        else
        {
            print("Age3 is greater");
        }
    }
    else
    {
        if(age2>age3)
        {
            print("Age2 is greater");
        }
        else
        {
            print("Age3 is greater");
        }
    }
4)  ElseIf or Ladder If--else:
It will contain If, Multiple Else if and Single 
Else Statement that 
will execute step by step.
if(condition)
{
    Statement;
}
else if(condition)
{
    Statement;
}
...
else
{
     Statement;
}
void main()
{
    int age1=60;
    int age2=70;
    int age3=40;
    if(age1>age2 && age1>age3)
    {
        print("Age1 is greater");
    }
    else if(age2>age3)
    {
        print("Age2 is greater");
    }
    else
    {
        print("Age3 is greater");
    }
    
}
5)  Multiple If:
It is used to solve the program where multiple conditions can be true.
if(condition)
{
}
if(condition)
{
}
     
Write a program to check that number is divisible by 3 and 5 both and independent?
void main()
{
    int num=2;
    if(num%3==0)
    {
        print("Divisible by 3");
    }
    if(num%5==0)
    {
        print("Divisible by 5");
    }
}
Assignment:
1) WAP to check Leap Year using Ternary and Simple If?
2) WAP to check vowel and consonant using Ternary and Simple If?
3) WAP to deduction in electricity  bill 50% if consumption is below 100 unit?
4) WAP to find max age in three person age using ternary?
5) WAP to check that user entered numeric char, alphabetical char or specials
using Ternary?
6) WAP to check middle age into three person?
7) WAP to create marksheet of 12th class student with all possibilities?
   (pass,fail,supp, pass by grace, distinction)
8) WAP to check vowel consonet without && and ||
do--while Loop:
First Execute program then check condition means by default one time loop will execute in all situation.
Syntax of do--while
init;
do
{
    statement;
    increment;
}while(condition);
Nested for loop:
it contains more than one for loop using nested sequence, it contains collection of outer for loop and inner for loop. where outer for loop execute once and inner for loop will be executed until condition is true.when outer for loop false program will terminate.
for(int i=1;i<=5;i++)
{
    for(int j=1;j<=i;j++)
    {
       print(i);
    }
}
i   j
1   1
2   2
3   3
4   4
5   5
.....................................................
1
2 3
4 5 6
7 8 9 10
.....................................
A a B b C
A a B b
A a B
A a
A
............................
A B C D E
  A B C D
    A B C
      A B
        A
.................................
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
...............................
1 0 0 1 0
1 0 0 1
1 0 0
1 0
1
.........................
A M I T
A M I
A M
A
.........................
print series of prime number where range will be entered by the user?
WAP to print the leap year range will be entered by the user?
    *
  * * *
* * * *  *
  * * *
    *
Dart Collection
This section will help you to learn about the collection in Dart. 
Here you will learn the following topics:
List in Dart,
Set in Dart,
Map in Dart and
Where in Dart.
List In Dart
If you want to store multiple values in the single variable with proper sequence, 
then we use List. 
List in dart is similar to Array in other programming languages.
E.g. to store the names of multiple students
you can use a List. The List is represented by Square Braces[].
How To Create List
You can create a List by specifying the initial elements in a square bracket.
 Square bracket [] is used to represent a List.
Syntax of List:
List<Datatype> variablename = [values,...]
// Integer List
List<int> ages = [10, 30, 23];
// String List
List<String> names = ["Raj", "John", "Rocky"];
// Mixed List
var mixed = [10, "John", 18.8];
Types Of Lists
1) Fixed Length List
2) Growable List [Mostly Used]
Fixed Length List
The fixed-length Lists are defined with the specified length. You cannot change the size at 
runtime. This will create List of 5 integers with the value 0.
void main()
{
    List<int> arr = List<int>.filled(5, 0);
    arr[0] = 10;
    arr[1] = 20;
    arr[2] = 30;
    arr[3] = 40;
    arr[4] = 50;
    
    
    print("Array elements are:");
    for(int i=0;i<arr.length;i++)
    {
        print(arr[i]);
    }
}
 The length of the growable List can be changed in runtime.
void main() {  
   var list1 = [210,21,22,33,44,55];  
   print(list1);  
}  
void main()
{
    List<int> arr = [10,20,30,40,50];
    arr.add(60);
    arr.add(70);
    print("Array elements are:");
    for(int i=0;i<arr.length;i++)
    {
        print(arr[i]);
    }
}
For more, see the example below.
void main(){  
   List<String> names = ["Raj", "John", "Rocky"];
   names[1] = "Bill";
   names[2] = "Elon";
   print(names);
}
Mutable And Immutable List
A mutable List means it can change after the declaration, and an immutable List can’t change 
after the declaration.
List<String> names = ["Raj", "John", "Rocky"]; // Mutable List
names[1] = "Bill"; // possible
names[2] = "Elon"; // possible
    
const List<String> names = ["Raj", "John", "Rocky"]; // Immutable List
names[1] = "Bill"; // not possible
names[2] = "Elon"; // not possible
List Properties In Dart
first: It returns the first element in the List.
last: It returns the last element in the List.
isEmpty: It returns true if the List is empty and false if the List is not empty.
isNotEmpty: It returns true if the List is not empty and false if the List is empty.
length: It returns the length of the List.
reversed: It returns a List in reverse order.
single: It is used to check if the List has only one element and returns it.
Access First And Last Elements Of List
You can access the first and last elements in the List by:
void main() {
   List<String> drinks = ["water", "juice", "milk", "coke"];
   print("First element of the List is: ${drinks.first}");
   print("Last element of the List is: ${drinks.last}");
}  
Check The List Is Empty Or Not
You can also check List contain any elements inside it or not. It will give result 
either in true or in false.
void main() {
   List<String> drinks = ["water", "juice", "milk", "coke"];
   List<int>  ages = [];
   print("Is drinks Empty: "+drinks.isEmpty.toString());
   print("Is drinks not Empty: "+drinks.isNotEmpty.toString());
   print("Is ages Empty: "+ages.isEmpty.toString());
   print("Is ages not Empty: "+ages.isNotEmpty.toString());
   
}  
Reverse List In Dart
You can easily reverse List by using .reversed properties. Here is an example below:
void main() {
   List<String> drinks = ["water", "juice", "milk", "coke"];
   print("List in reverse: ${drinks.reversed}");
}  
Dart provides four methods to insert the elements into the Lists. These methods are 
given below.
Method	Description
add()	Add one element at a time and returns the modified List object.
addAll()	Insert the multiple values to the given List, 
                and each value is separated by the commas and enclosed with a 
                square bracket ([]).
insert()	Provides the facility to insert an element at a specified index position.
insertAll()	Insert the multiple value at the specified index position.
Example 1: Add Item To List
In this example below, we are adding an item to evenList using add() method.
void main() {  
    var evenList = [2,4,6,8,10];  
    print(evenList);  
    evenList.add(12);  
    print(evenList);  
}  
Example 2: Add Items To List
In this example below, we are adding items to evenList using addAll() method.
void main() {
  var evenList = [2, 4, 6, 8, 10];
  print(evenList);
  evenList.addAll([12, 14, 16, 18]);
  print(evenList);
}
Example 3: Insert Item To List
In this example below, we are adding an item to myList using insert() method.
void main() {
  List myList = [3, 4, 2, 5];
  print(myList);
  myList.insert(2, 15);
  print(myList);
}
**Example 4: Insert Items To List **
In this example below, we are adding items to myList using insertAll() method.
void main() {
  var myList = [3, 4, 2, 5];
  print(myList);
  myList.insertAll(1, [6, 7, 10, 9]);
  print(myList);
}
  
Removing List Elements
Method	Description
remove()	Removes one element at a time from the given List.
removeAt()	Removes an element from the specified index position and returns it.
removeLast()	Remove the last element from the given List.
removeRange()	Removes the item within the specified range.
Example 1: Removing List Item From List
In this example below, we are removing item of List using remove() method.
void main() {
  var list = [10, 20, 30, 40, 50];
  print("List before removing element : ${list}");
  list.remove(30);
  print("List after removing element : ${list}");
}
Combine Two Or More List In Dart
You can combine two or more Lists in dart by using spread syntax.
void main() {
  List<String> names = ["Raj", "John", "Rocky"];
  List<String> names2 = ["Mike", "Subash", "Mark"];
  List<String> allNames = [...names, ...names2];
  print(allNames);
}
Conditions In List
You can also use conditions in List. Here sad = false so cart doesn’t contain Beer in it.
void main() {
  bool sad = true
  var cart = ['milk', 'ghee', if (sad) 'Beer'];
  print(cart);
}
Where In List Dart
You can use where with List to filter specific items. Here in this example, even numbers are only filtered.
void main(){
List<int> numbers = [2,4,6,8,10,11,12,13,14];
List<int> even = numbers.where((number)=> number.isEven).toList(); 
print(even);
}
1) WAP to display unique element in List?
2) Write a program to count total frequency of each element in list?
3) Write a program to reverse non prime element in list?
4) Write a program to split even and odd element from list?
5) Write a program to sort list element in desc order?
6) Write a program to find max and second max element in List?
Set In Dart
Set is a unique collection of items. You cannot store duplicate values in the Set. 
It is unordered, so it can be faster than lists while working with a large amount of data. Set is useful when you need to store unique values without considering the order of the input. E.g., fruits name, months name, days name, etc. It is represented by Curley Braces{}.
Syntax
Set <variable_type> variable_name = {};
You can create a Set in Dart using the Set type annotation. Here Set<String> means only text is allowed in the Set.
void main(){
  Set<String> fruits = {"Apple", "Orange", "Mango"};
  print(fruits);
}
Set Properties In Dart
Properties	Work
first	To get first value of Set.
last	To get last value of Set.
isEmpty	Return true or false.
isNotEmpty	Return true or false.
length	It returns the length of the Set.
Example of Set Properties Dart
This example finds the first and last element of the Set, checks whether it is empty or not, and finds its length.
void main() {
  // declaring fruits as Set
  Set<String> fruits = {"Apple", "Orange", "Mango", "Banana"};
  // using different properties of Set
  print("First Value is ${fruits.first}");
  print("Last Value is ${fruits.last}");
  print("Is fruits empty? ${fruits.isEmpty}");
  print("Is fruits not empty? ${fruits.isNotEmpty}");
  print("The length of fruits is ${fruits.length}");
}
Add & Remove Items In Set
Like lists, you can add or remove items in a Set. To add items use add() method and to remove use remove() method.
Method	Description
add()	Add one element to Set.
remove()	Removes one element from Set.
void main(){
 Set<String> fruits = {"Apple", "Orange", "Mango"};
  
  fruits.add("Lemon");
  fruits.add("Grape");
  
  print("After Adding Lemon and Grape: $fruits");
  
  fruits.remove("Apple");
  print("After Removing Apple: $fruits");
}
Adding Multiple Elements
You can use addAll() method to add multiple elements from the list to Set.
Method	Description
addAll()	Insert the multiple values to the given Set.
void main(){
 Set<int> numbers = {10, 20, 30};
  numbers.addAll([40,50]);
 print("After adding 40 and 50: $numbers");
}    
Printing All Values In Set
You can print all Set items by using loops. Click here if you want to learn loop in dart.
void main(){
 Set<String> fruits = {"Apple", "Orange", "Mango"};
  
 for(String fruit in fruits){
   print(fruit);
 }
}
Set Methods In Dart
Some other helpful Set methods in dart.
Method	Description
clear()	Removes all elements from the Set.
difference()	Creates a new Set with the elements of this that are not in other.
elementAt()	Returns the index value of element.
intersection()	Find common elements in two sets.
Map In Dart:
In a Map, data is stored as keys and values. In Map, each key must be unique. 
They are similar to HashMaps and Dictionaries in other languages.
How To Create Map In Dart
Here we are creating a Map for String and String. It means keys and values
 must be the type of String. You can create a Map of any kind as you like.
void main(){
Map<String, String> countryCapital = {
  'USA': 'Washington, D.C.',
  'India': 'New Delhi',
  'China': 'Beijing'
};
  print(countryCapital);
}
Access Value From Key
You can find the value of Map from its key. Here we are printing Washington,
 D.C. by its key, i.e., USA.
void main(){
Map<String, String> countryCapital = {
  'USA': 'Washington, D.C.',
  'India': 'New Delhi',
  'China': 'Beijing'
};
  print(countryCapital["USA"]);
}
Map Properties In Dart
Properties	Work
keys	To get all keys.
values	To get all values.
isEmpty	Return true or false.
isNotEmpty	Return true or false.
length	It returns the length of the Map.
Example Of Map Properties In Dart
This example finds all keys/values of Map, the first and last element,
 checks whether it is empty or not, and finds its length.
void main() {
 
  Map<String, double> expenses = {
    'sun': 3000.0,
    'mon': 3000.0,
    'tue': 3234.0,
  };
  
  print("All keys of Map: ${expenses.keys}");
  print("All values of Map: ${expenses.values}");
  print("Is Map empty: ${expenses.isEmpty}");
  print("Is Map not empty: ${expenses.isNotEmpty}");
  print("Length of map is: ${expenses.length}");
}
Adding Element To Map
If you want to add an element to the existing Map. Here is the way for you:
void main(){
Map<String, String> countryCapital = {
  'USA': 'Washington, D.C.',
  'India': 'New Delhi',
  'China': 'Beijing'
};
  // Adding New Item
  countryCapital['Japan'] = 'Tokio';
  print(countryCapital);
}
Updating An Element Of Map
If you want to update an element of the existing Map. Here is the way for you:
void main(){
Map<String, String> countryCapital = {
  'USA': 'Nothing',
  'India': 'New Delhi',
  'China': 'Beijing'
};
  // Updating Item
  countryCapital['USA'] = 'Washington, D.C.';
  print(countryCapital);
}
Map Methods In Dart
Some useful Map methods in dart.
Properties	Work
keys.toList()	Convert all Maps keys to List.
values.toList()	Convert all Maps values to List.
containsKey(‘key’)	Return true or false.
containsValue(‘value’)	Return true or false.
clear()	Removes all elements from the Map.
removeWhere()	Removes all elements from the Map if condition is valid.
Convert Maps Keys & Values To List
Let’s convert keys and values of Map to List.
void main() {
 
  Map<String, double> expenses = {
    'sun': 3000.0,
    'mon': 3000.0,
    'tue': 3234.0,
  };
  
  // Without List
  print("All keys of Map: ${expenses.keys}");
  print("All values of Map: ${expenses.values}");
 
  // With List
  print("All keys of Map with List: ${expenses.keys.toList()}");
  print("All values of Map with List: ${expenses.values.toList()}");
  
}
Check Map Contains Specific Key/Value Or Not?
Let’s check whether the Map contains a specific key/value in it or not.
void main() {
 
  Map<String, double> expenses = {
    'sun': 3000.0,
    'mon': 3000.0,
    'tue': 3234.0,
  };
  
  // For Keys
  print("Does Map contain key sun: ${expenses.containsKey("sun")}");
  print("Does Map contain key abc: ${expenses.containsKey("abc")}");
 
  // For Values
  print("Does Map contain value 3000.0: ${expenses.containsValue(3000.0)}");
  print("Does Map contain value 100.0: ${expenses.containsValue(100.0)}");
  
}
Removing Items From Map
Suppose you want to remove an element of the existing Map. Here is the way for you:
void main(){
Map<String, String> countryCapital = {
  'USA': 'Nothing',
  'India': 'New Delhi',
  'China': 'Beijing'
};
  
  countryCapital.remove("USA");
  print(countryCapital);
}
Looping Over Element Of Map
You can use any loop in Map to print all keys/values or to perform operations in its keys and values.
void main(){
  Map<String, dynamic> book = {
    'title': 'Misson Mangal',
    'author': 'Kuber Singh',
    'page': 233
  };
  
 // Loop Through Map
  for(MapEntry book in book.entries){
    print('Key is ${book.key}, value ${book.value}');
  }
}
Looping In Map Using For Each
In this example, you will see how to use a loop to print all the keys and values in Map.
void main(){
  Map<String, dynamic> book = {
    'title': 'Misson Mangal',
    'author': 'Kuber Singh',
    'page': 233
  };
  
  
 // Loop Through For Each
  book.forEach((key,value)=> print('Key is $key and value is $value'));
  
}
Remove Where In Dart Map
In this example, you will see how to get students whose marks are greater or equal to 32 using where method.
void main() {
  Map<String, double> mathMarks = {
    "ram": 30,
    "mark": 32,
    "harry": 88,
    "raj": 69,
    "john": 15,
  };
  mathMarks.removeWhere((key, value) => value < 32);
  print(mathMarks);
}
Dart File Handling:
This section will help you to handle files in Dart. File handling is an important part of 
any programming language. Here you will learn the following topics:
Read File in Dart,
Write File in Dart,
Delete File in Dart,
Introduction
In this section, you will learn how to write file in dart programming language by using File
 class and writeAsStringSync() method.
Write File In Dart
Let’s create a file named test.txt in the same directory of your dart program and write some text in it.
// dart program to write to file
import 'dart:io';
void main() {
  // open file
  File file = File('test.txt');
  // write to file
  file.writeAsStringSync('Welcome to test.txt file.');
  print('File written.');
}
Add New Content To Previous Content
You can use FileMode.append to add new content to previous content. Assume that test.txt file already contains some text.
Welcome to test.txt file.
Now, let’s add new content to it.
// dart program to write to existing file
import 'dart:io';
void main() {
  // open file
  File file =  File('test.txt');
  // write to file
  file.writeAsStringSync('\nThis is a new content.', mode: FileMode.append);
  print('Congratulations!! New content is added on top of previous content.');
}
Write CSV File In Dart
In the example below, we will ask user to enter name and phone of 3 students and write it to a csv file named students.csv.
// dart program to write to csv file
import 'dart:io';
void main() {
  // open file
  File file = File("students.csv");
  // write to file
  file.writeAsStringSync('Name,Phone\n');
  for (int i = 0; i < 3; i++) {
    // user input name
    stdout.write("Enter name of student ${i + 1}: ");
    String? name = stdin.readLineSync();
    stdout.write("Enter phone of student ${i + 1}: ");
    // user input phone
    String? phone = stdin.readLineSync();
    file.writeAsStringSync('$name,$phone\n', mode: FileMode.append);
  }
  print("Congratulations!! CSV file written successfully.");
}
Introduction To File Handling
File handling is an important part of any programming language. In this section, you will learn how to read the file in a dart programming language.
Read File In Dart
Assume that you have a file named test.txt in the same directory of your dart program.
Welcome to test.txt file.
This is a test file.
// dart program to read from file
import 'dart:io';
void main() {
  // creating file object
  File file = File('test.txt');
  // read file
  String contents = file.readAsStringSync();
  // print file
  print(contents);
}
Get File Information
In this example below, you will learn how to get file information like file location, file size, and last modified time.
import 'dart:io';
void main() {
  // open file
  File file = File('test.txt');
  // get file location
  print('File path: ${file.path}');
  // get absolute path
  print('File absolute path: ${file.absolute.path}');
  // get file size
  print('File size: ${file.lengthSync()} bytes');
  // get last modified time
  print('Last modified: ${file.lastModifiedSync()}');
}
Read CSV File In Dart
Assume that you have a CSV file named test.csv in the same directory of your dart program.
Name,Email,Phone
John, john@gmail.com, 1234567890
Smith, smith@gmail.com, 0987654321
Now, you can read this file using File class and readAsStringSync() method. We will use split() method to split the string into a list of strings.
// dart program to read from csv file
import 'dart:io';
void main() {
  // open file
  File file = File('test.csv');
  // read file
  String contents = file.readAsStringSync();
  // split file using new line
  List<String> lines = contents.split('\n');
  // print file
  print('---------------------');
  for (var line in lines) {
    print(line);
  }
}
Read File From Specific Directory
To read a file from a specific directory, you need to provide the full path of the file. Here is an example to read file from a specific directory.
// dart program to read from file
import 'dart:io';
void main() {
  // open file
  File file = File('C:\\Users\\test.txt');
  // read file
  String contents = file.readAsStringSync();
  // print file
  print(contents);
}
Introduction
In this section, you will learn how to delete file in dart programming language using File class and deleteSync() method.
Delete File In Dart
Assume that you have a file named test.txt in the same directory of your dart program. Now, let’s delete it.
// dart program to delete file
import 'dart:io';
void main() {
  // open file
  File file = File('test.txt');
  // delete file
  file.deleteSync();
  print('File deleted.');
}
Function in dart:
Functions are the block of code that performs a specific task. it is basically used to 
sub-divide the program code into multiple sub unit.it is also used to reduce common code  repetition means The function helps reusability 
of the code in the program.
Why Function
1) Avoid Code Repetition
2) Easy to divide the complex program into smaller parts
3) Helps to write a clean code
Syntax of Function:
returntype functionName(parameter1,parameter2, ...){
  // function body
}
Naming Convention
In dart function are also objects.
You should follow the lowerCamelCase naming convention while naming function.
You should follow the lowerCamelCase naming convention while naming function parameters
Types Of Function
Functions are the block of code that performs a specific task. 
Here are different types of functions:
No Parameter And No Return Type:
void functionName()
{
   Statements;
}
e.g
void additionOfNumber() {
  int a=10,b=20;
  int sum = a + b;
  print("Sum of $a and $b is $sum");
}
void main(){
    additionOfNumber();
}
Parameter And No Return Type:
void functionName(param)
{
   Statements;
}
example:
void additionOfNumber(int a, int b) {
  int sum = a + b;
  print("Sum of $a and $b is $sum");
}
void main(){
    additionOfNumber(10,20);
}
datatype functionName()
{
   return data;
}
example:
int additionOfNumber() {
  int a=10,b=20;
  int sum = a + b;
  return sum;
}
void main(){
    int res = additionOfNumber();
    print("result is $res");
}
datatype functionName(param)
{
   return data;
}
Example:int additionOfNumber(int a,int b) {
  int sum = a + b;
  return sum;
}
void main(){
    int res = additionOfNumber(100,20);
    print("result is $res");
}
Write a program to calculate simple interest?
double siCalc(double a,double b, double c) {
  double res = (a*b*c)/100;
  return res;
}
void main(){
    double res = siCalc(100000,2,2);
    print("result is $res");
    res = siCalc(200000,2,2);
    print("result is $res");
    res = siCalc(300000,2,2);
    print("result is $res");
}
void swap(int a, int b){
    int temp=a;
    a=b;
    b=temp;
    print("a: $a, b: $b");
}
void main()
{
    swap(100,20);
}
Anonymous Function In Dart
This tutorial will teach you the anonymous function and how to use it. 
You already saw function like main(), add(), etc. These are the named functions, which means they have a certain name.
But not every function needs a name. If you remove the return type and the function name, the function is called anonymous function.
Syntax
Here is the syntax of the anonymous function.
(parameterList){
// statements
}
Example 1: Anonymous Function In Dart
In this example, you will learn to use an anonymous function to print all list items. This function invokes each fruit without having a function name.
void main() {
  const fruits = ["Apple", "Mango", "Banana", "Orange"];
  fruits.forEach((fruit) {
    print(fruit);
  });
}
Arrow Function In Dart
Dart has a special syntax for the function body, which is only one line. The arrow function is represented by => symbol. It is a shorthand syntax for any function that has only one expression.
Syntax
The syntax for the dart arrow function.
returnType functionName(parameters...) => expression;
// arrow function that calculate interest
double calculateInterest(double principal, double rate, double time) =>
    principal * rate * time / 100;
void main() {
  double principal = 5000;
  double time = 3;
  double rate = 3;
  double result = calculateInterest(principal, rate, time);
  print("The simple interest is $result.");
}
Simple Calculation Using Arrow Function
This program finds the sum, difference, multiplication, and division of two numbers using the arrow function.
int add(int n1, int n2) => n1 + n2;
int sub(int n1, int n2) => n1 - n2;
int mul(int n1, int n2) => n1 * n2;
double div(int n1, int n2) => n1 / n2;
void main() {
  int num1 = 100;
  int num2 = 30;
  print("The sum is ${add(num1, num2)}");
  print("The diff is ${sub(num1, num2)}");
  print("The mul is ${mul(num1, num2)}");
  print("The div is ${div(num1, num2)}");
}
Static Component In Dart
If you want to define a variable or method that is shared by all instances of a class,
using static keyword. 
Static members are accessed using the class name. It is used for memory management.
How To Declare A Static Variable In Dart
static datatype variablename;
How To Initialize A Static Variable In Dart
To initialize a static variable simply assign a value to it.
class ClassName {
  static dataType variableName = value;
  // for e.g 
  // static int num = 10;
  // static String name = "Dart";
}
How To Access A Static Variable In Dart
You need to use the ClassName.variableName to access a static variable in Dart.
class ClassName {
  static dataType variableName = value;
  // Accessing the static variable inside same class
  void display() {
    print(variableName);
  }
}
void main() {
  // Accessing static variable outside the class
  dataType value =ClassName.variableName;
}
Dart Static Method
A static method is shared by all instances of a class. 
It is declared using the static keyword. You can access a static method without creating 
an object of the class.
Syntax
class ClassName{
static returnType methodName(){
  //statements
}
}
An example to pass multiple student marks and calculate average?
class StuMarks
{
    static List<int> marks = [];
    static int? avg;
    StuMarks(int m)
    {
        marks.add(m);
    }
   static void calculate()
    {
        int sum = 0;
        for(int i = 0; i < marks.length; i++)
        {
            sum += marks[i];
        }
        avg = sum ~/ marks.length;
    }
   static void display()
    {
        print("Marks: $avg");
    }
}
void main()
{
    var s1 = StuMarks(90);
    var s2 = StuMarks(80);
    var s3 = StuMarks(70);
    StuMarks.calculate();
    StuMarks.display();
    
    
}
Constructor In Dart
A constructor is a special method used to initialize an object.
 It is called automatically when an object is created, and it can be used to set the initial 
values for the object’s properties. For example, the following code creates a Person class 
object and sets the initial values for the name and age properties.
Example 1: How To Declare Constructor In Dart
In this example below, there is a class Student with three properties: name, age, and rollNumber. The class has one constructor. The constructor is used to initialize the values of the three properties. We also created an object of the class Student called student.
class Student {
  String? name;
  int? age;
  int? rollNumber;
  // Constructor
  Student(String name, int age, int rollNumber) {
    print(
        "Constructor called"); // this is for checking the constructor is called or not.
    this.name = name;
    this.age = age;
    this.rollNumber = rollNumber;
  }
}
void main() {
  // Here student is object of class Student.
  Student student = Student("John", 20, 1);
  print("Name: ${student.name}");
  print("Age: ${student.age}");
  print("Roll Number: ${student.rollNumber}");
}
Write Constructor Single Line
You can also write the constructor in short form. You can directly assign the values to the properties. For example, the following code is the short form of the constructor in one line.
class Person{
  String? name;
  int? age;
  String? subject;
  double? salary;
  // Constructor in short form
  Person(this.name, this.age, this.subject, this.salary);
  // display method
  void display(){
    print("Name: ${this.name}");
    print("Age: ${this.age}");
    print("Subject: ${this.subject}");
    print("Salary: ${this.salary}");
  }
}
void main(){
  Person person = Person("John", 30, "Maths", 50000.0);
  person.display();
Type of Constructor:
1) Default Constructor or No Argument Based Constructor:
Example 1: Default Constructor In Dart
In this example below, there is a class Laptop with two properties: brand, and price. Lets create constructor with no parameter and print something from the constructor. We also have an object of the class Laptop called laptop.
class Laptop {
  String? brand;
  int? price;
  // Constructor
  Laptop() {
    print("This is a default constructor");
  }
}
void main() {
  // Here laptop is object of class Laptop.
  Laptop laptop = Laptop();
}
Parameterized Constructor or With Argument Constructor:
Parameterized constructor is used to initialize the instance variables of the class. 
Parameterized constructor is the constructor that takes parameters.
 It is used to pass the values to the constructor at the time of object creation.
Syntax
class ClassName {
  // Instance Variables
  int? number;
  String? name;
  // Parameterized Constructor
  ClassName(this.number, this.name);
}
Named Constructor In Dart:
We can provide special unique name constructor and it will be called using Assigned name.
In this example below, there is a class Student with three properties: 
name, age, and rollNumber. 
The class has two constructors. The first constructor is a default constructor. 
The second constructor is a named constructor. 
The named constructor is used to initialize the values of the three properties.
 We also have an object of the class Student called student.
class Student {
  String? name;
  int? age;
  int? rollNumber;
  // Default Constructor
  Student() {
    print("This is a default constructor");
  }
  // Named Constructor
  Student.namedConstructor(String name, int age, int rollNumber) {
    this.name = name;
    this.age = age;
    this.rollNumber = rollNumber;
  }
}
void main() {
  // Here student is object of class Student.
  Student student = Student.namedConstructor("John", 20, 1);
  print("Name: ${student.name}");
  print("Age: ${student.age}");
  print("Roll Number: ${student.rollNumber}");
}
class Person
{
    String? name;
    int? age;
    Person(this.name, this.age);
    Person.guest()
    {
        name = "Guest";
        age = 18;
    }
    Person.elder(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
    void showOutput()
    {
        print(name);
        print(age);
    }
}
void main()
{
    var p1 = Person("Peter", 23);
    var p2 = Person.guest();
    var p3 = Person.elder("Sam", 45);
    p1.showOutput();
    p2.showOutput();
    p3.showOutput();
}
Constant constructor is a constructor that creates a constant object. 
A constant object is an object whose value cannot be changed. 
A constant constructor is declared using the keyword const.
In this example below, there is a class Point with two final properties: x and y. 
The class also has a constant constructor that initializes the two properties. 
The class also has a method called display, 
which prints out the values of the two properties.
class Point {
  final int x;
  final int y;
  const Point(this.x, this.y);
}
void main() {
  // p1 and p2 has the same hash code.
  Point p1 = const Point(1, 2);
  print("The p1 hash code is: ${p1.hashCode}");
  Point p2 = const Point(1, 2);
  print("The p2 hash code is: ${p2.hashCode}");
  // without using const
  // this has different hash code.
  Point p3 = Point(2, 2);
  print("The p3 hash code is: ${p3.hashCode}");
  Point p4 = Point(2, 2);
  print("The p4 hash code is: ${p4.hashCode}");
}
Encapsulation in Dart
In Dart, Encapsulation means hiding data within a library, preventing it from outside 
factors.
 It helps you control your program and prevent it from becoming too complicated.
How to implement encapsulation practically:
Getter and Setter Methods
Getter and setter methods are used to access and update the value of private property. 
Getter methods are used to access the value of private property. Setter methods are used to 
update the value of private property.
We should create getter for read data of variable and setter to write data on variable.
Example 1: Encapsulation In Dart
In this example, we will create a class named Employee. The class will have two private properties _id and _name. We will also create two public methods getId() and getName() to access the private properties. We will also create two public methods setId() and setName() to update the private properties.
class Employee {
  // Private properties
  int? _id;
  String? _name;
// Getter method to access private property _id
  int getId() {
    return _id!;
  }
// Getter method to access private property _name
  String getName() {
    return _name!;
  }
// Setter method to update private property _id
  void setId(int id) {
    this._id = id;
  }
// Setter method to update private property _name
  void setName(String name) {
    this._name = name;
  }
  
}
void main() {
  // Create an object of Employee class
  Employee emp = new Employee();
  // setting values to the object using setter
  emp.setId(1);
  emp.setName("John");
  // Retrieve the values of the object using getter
  print("Id: ${emp.getId()}");
  print("Name: ${emp.getName()}");
}
Private Properties
Private property is a property that can only be accessed from same library. Dart does not have any keywords like private to define a private property. You can define it by prefixing an underscore (_) to its name.
Example 2: Private Properties In Dart
In this example, we will create a class named Employee. The class has one private property _name. We will also create a public method getName() to access the private property.
class Employee {
  // Private property
  var _name;
  // Getter method to access private property _name
  String getName() {
    return _name;
  }
  // Setter method to update private property _name
  void setName(String name) {
    this._name = name;
  }
}
void main() {
  var employee = Employee();
  employee.setName("Jack");
  print(employee.getName());
}
Why Encapsulation Is Important?
Data Hiding: Encapsulation hides the data from the outside world. 
It prevents the data from being accessed by the code outside the class. This is known as data hiding.
Testability: Encapsulation allows you to test the class in isolation.
 It will enable you to test the class without testing the code outside the class.
Flexibility: Encapsulation allows you to change the implementation of the class without 
affecting the code outside the class.
Security: Encapsulation allows you to restrict access to the class members. 
It will enable you to limit access to the class members from the code outside the library.
Data Abstraction:
it is used to hide the actual implementation of code to provide better security 
and accessibility.
Dart provide abstract class and interface concept to hide actual implementation of code.
abstract class Bank
{
    void transaction(); //Null
}
class Customer extends Bank
{
 void transaction(){
     code......
}
}
void Main()
{
       Bank obj = Customer();
       obj.transaction();
}
Polymorphism In Dart
Poly means many and morphism means forms. Polymorphism is the ability of an object to take 
on many forms. As humans, we have the ability to take on many forms. We can be a student,
 a teacher, a parent, a friend, and so on. 
Similarly, in object-oriented programming, polymorphism is the ability of an object to take on many forms.
Polymorphism By Method Overriding
Method overriding is a technique in which you can create a method in the child class 
that has the same name as the method in the parent class.
 The method in the child class overrides the method in the parent class.
Syntax
class ParentClass{
void functionName(){
  }
}
class ChildClass extends ParentClass{
@override 
void functionName(){
  }
}
Example 1: Polymorphism By Method Overriding In Dart
In this example below, there is a class named Animal with a method named eat(). 
The eat() method is overridden in the child class named Dog.
class Animal {
  void eat() {
    print("Animal is eating");
  }
}
class Dog extends Animal {
  @override
  void eat() {
    print("Dog is eating");
  }
}
void main() {
  Animal animal = Animal();
  animal.eat();
  Dog dog = Dog();
  dog.eat();
    Animal animal2 = Dog();
    animal2.eat();
}
 
Inheritance is a sharing of behavior between two classes. It allows you to define a 
class that extends the functionality of another class. means it provide 100% code reusability 
and relationship between classes.
 
The extend keyword is used for inheriting from parent class.
Dart supports single inheritance, which means that a class can only inherit from a single class. Dart does not support multiple inheritance which means that a class cannot inherit from multiple classes.
class ParentClass {
  // Parent class code
}
class ChildClass extends ParentClass {
  // Child class code
}
Example 1:
class Person {
  // Properties
  String? name;
  int? age;
  // Method
  void display() {
    print("Name: $name");
    print("Age: $age");
  }
}
// Here In student class, we are extending the
// properties and methods of the Person class
class Student extends Person {
  // Fields
  String? schoolName;
  String? schoolAddress;
  // Method
  void displaySchoolInfo() {
    print("School Name: $schoolName");
    print("School Address: $schoolAddress");
  }
}
void main() {
  // Creating an object of the Student class
  var student = Student();
  student.name = "John";
  student.age = 20;
  student.schoolName = "ABC School";
  student.schoolAddress = "New York";
  student.display();
  student.displaySchoolInfo();
}
Advantages Of Inheritance In Dart
It promotes reusability of the code and reduces redundant code.
It helps to design a program in a better way.
It makes code simpler, cleaner and saves time and money on maintenance.
It facilitates the creation of class libraries.
It can be used to enforce standard interface to all children classes.
Types Of Inheritance In Dart
Single Inheritance - In this type of inheritance, a class can inherit from only one class. 
In Dart, we can only extend one class at a time.
Multilevel Inheritance - In this type of inheritance, a class can inherit from another
 class and that class can also inherit from another class. In Dart, we can extend 
a class from another class which is already extended from another class.
Hierarchical Inheritance - In this type of inheritance, parent class is inherited 
by multiple subclasses. For example, the Car class can be inherited by the Toyota class 
and Honda class.
Multiple Inheritance - In this type of inheritance, a class can inherit from multiple classes. Dart does not support multiple inheritance. For e.g. Class Toyota extends Car, Vehicle {} is not allowed in Dart.
Abstract Class in Dart
Introduction
In this section, you will learn about dart abstract class. Before learning about abstract
 class, you should have a basic understanding of class, object, constructor, and inheritance. 
Previously you learned how to define a class. These classes are concrete classes. 
You can create an object of concrete classes, but you cannot create an object of 
abstract classes.
Abstract Class
Abstract classes are classes that cannot be initialized. It is used to define the behavior
 of a class that can be inherited by other classes. An abstract class is declared using the
 keyword abstract.
abstract class ClassName {
  //Body of abstract class
  method1();
  method2();
}
Example
abstract class Vehicle {
  // Abstract method
  void start();
  // Abstract method
  void stop();
}
class Car extends Vehicle {
  // Implementation of start()
  @override
  void start() {
    print('Car started');
  }
  // Implementation of stop()
  @override
  void stop() {
    print('Car stopped');
  }
}
class Bike extends Vehicle {
  // Implementation of start()
  @override
  void start() {
    print('Bike started');
  }
  // Implementation of stop()
  @override
  void stop() {
    print('Bike stopped');
  }
}
void main() {
  Car car = Car();
  car.start();
  car.stop();
  Bike bike = Bike();
  bike.start();
  bike.stop();
}
Interface in Dart
Introduction
In this section, you will learn the dart interface and how to implement an interface 
with the help of examples. In Dart, every class is implicit interface. 
Before learning about the interface in dart, you should have a basic 
understanding of the class and objects, inheritance and abstract class in Dart.
Interface In Dart
An interface defines a syntax that a class must follow. It is a contract that defines 
the capabilities of a class. It is used to achieve abstraction in the Dart programming 
language. When you implement an interface, you must implement all the properties and 
methods defined in the interface. Keyword implements is used to implement an interface.
class InterfaceName {
  // code
}
class ClassName implements InterfaceName {
  // code
}
In dart there is no keyword interface but you can use class or abstract class to declare
 an interface. All classes implicitly define an interface. Mostly abstract class is used 
to declare an interface.
// creating an interface using abstract class
abstract class Person {
  canWalk();
  canRun();
}
Implementing Interface In Dart
You must use the implements keyword to implement an interface. The class that implements 
an interface must implement all the methods and properties of the interface.
class Student implements Person {
 // implementation of canWalk()
  @override
  canWalk() {
    print('Student can walk');
  }
// implementation of canRun()
  @override
  canRun() {
    print('Student can run');
  }
}
// abstract class as interface
abstract class Vehicle {
  void start();
  void stop();
}
// implements interface
class Car implements Vehicle {
  @override
  void start() {
    print('Car started');
  }
  @override
  void stop() {
    print('Car stopped');
  }
}
void main() {
  var car = Car();
  car.start();
  car.stop();
}
Mixin In Dart
Mixins are a way of reusing the code in multiple classes. Mixins are declared using 
the keyword mixin followed by the mixin name. 
Three keywords are used while working with mixins: 
mixin, with, and on. It is possible to use multiple mixins in a class.
 
Rules For Mixin
Mixin can’t be instantiated. You can’t create object of mixin.
Use the mixin to share the code between multiple classes.
Mixin has no constructor and cannot be extended.
It is possible to use multiple mixins in a class.
mixin Mixin1{
  // code
}
mixin Mixin2{
  // code
}
class ClassName with Mixin1, Mixin2{
  // code
}
mixin ElectricVariant {
  void electricVariant() {
    print('This is an electric variant');
  }
}
mixin PetrolVariant {
  void petrolVariant() {
    print('This is a petrol variant');
  }
}
// with is used to apply the mixin to the class
class Car with ElectricVariant, PetrolVariant {
  // here we have access of electricVariant() and petrolVariant() methods
}
void main() {
  var car = Car();
  car.electricVariant();
  car.petrolVariant();
}
0 تعليقات
POST Answer of Questions and ASK to Doubt