Categories
Dart

Dart Runes

Dart Runes are the UTF-32 unicode points of a string.

Unicode values are nothing but Standard for representing characters as integers.

Unicode defines a unique number value for each letter, digit and used in all of the world’s popular languages(Writing Systems);

For ex :

0 to 9, Capital letters(A,B,…,Y,Z) etc. have unique Unicode values to identify easily by the Machine.

Rune is nothing but an integer representing unicode codepoint.

For ex :

Character A has Rune value \u{0041} and Unicode is U+0041.

For More Details you should visit and check details at website.

Different emojis, letters and also digits have unique unicode codepoints. which implies they also have unique Rune Values(code points).

we can express a Unicode code point as \uXXXX, where XXXX is a 4-digit hexidecimal value. and u stands for unicode.

For ex :

the heart character (?) is \u2665.

To specify more or less than 4 hex digits in Runes, place the value in curly brackets.

For ex :

the thumbsup emoji (??) is \u{1f44d}.

For ex :

void main()
 {

        Runes clapping = new Runes("\u{0050}");
        print(clapping);
        print(new String.fromCharCodes(clapping));

        Runes input = new Runes('\u2665  \u{1f605}  \u{1f60e}  \u{1f47b}  \u{1f596}  \u{1f44d}');
        print(new String.fromCharCodes(input));
}

Output :

(80)
P
? ?? ?? ?? ?? ??

In dart, string class has several properties and methods to extract the rune information.

Runes Common Properties

For ex :

main() {
  Runes clapping = new Runes("\u{0050}");
  Runes clappingData = new Runes("ABCD");
  print(clappingData.first);
  print(clappingData.last);

  print(clapping.single);
  print(clapping.hashCode);
  print(clapping.runtimeType);
  print(clapping.isEmpty);
  print(clapping.isNotEmpty);
  print(clapping.length);
}

Output :

65
68
80
31123396
Runes
false
true
1

Runes Common Methods

For ex :

main() {
  Runes clappingData = new Runes("ABCD");
  print(clappingData.toString());
  print(clappingData.skip(1));
  print(clappingData.contains("C"));
  print(clappingData.contains((67)));
  print(clappingData.toList());
  print(clappingData.toSet());
}

Output :

(65, 66, 67, 68)
(66, 67, 68)
false
true
[65, 66, 67, 68]
{65, 66, 67, 68}

Practice different properties and methods of dart runes by yourself to understand the better use of it.

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 Maps

After the list data structure, we will learn one of the most important data structure i.e., Map.

Map also acts as the built in data type for dart programming language.

The map data structure has unique pattern of storing data in key-value pair.

The type of key and value in map can be of any data type.

Each key can occur only once(means every key should be unique), but you can use the same data for value multiple times. user can also provide any data to the value even NULL.

Maps can grow and shrink at runtime by adding the key-value pairs.

Maps in dart are supported using map literals(a notation for representing a fixed value) and map constructor.

Map using map literals

To declare a map, we need to enclose the key value pairs in between a pair of curly braces “{}”.

Syntax :

var variableMapName = { key:value, key2:value2, key3:value3 }

Map using map constructor

For ex :

void main() { 
  var dataMap = {'Name':'Bill','Surname':'Gates','Designation':'Developer'}; 
   print(dataMap); 
}

Output :

{ Name: Bill, Surname: Gates, Designation: Developer }

To declare a map using constructor, first create the map instance and then initialise the map objects.

Syntax :

var variableMap = Map(); // declare the map
variableMap [key] = value; // initialise the map

For ex :

void main() { 
   var deviceMap = {'Device':'Motorola','Model':'Moto G5','Manufacturer':'Motorola'}; 
   deviceMap['Brand'] = 'Google'; 
   print(deviceMap); 
}

Output :

{ Device: Motorola, Model: Moto G5, Manufacturer: Motorola, Brand: Google }

We can also define the data types for key-value pair at the time of map declaration.

For ex :

void main() { 
   var deviceMap = Map<String,int>(); 
   deviceMap['Age'] = 100; 
   deviceMap['Number'] = 200; 
   print(deviceMap); 
}

Output :

{Age: 100, Number: 200}

For above example, user can only pass the key of string data type and assign the value of Int data type. Otherwise, it will generate the compile time error as data type of key-value pair are defined already.

In this way you can define the data type for key value pair in dart maps.

Several built in properties and methods are defined to perform data related operations very quickly and efficiently.

Map Common Properties

For ex :

main(){
  var mapData=new Map<String,String>();
  mapData['King']="Arthur";
  mapData['Queen']="Alizabeth";
  mapData['Prince']="Harry";
  print(mapData);

  print(mapData.length);
  print(mapData.keys);
  print(mapData.values);
  print(mapData.isNotEmpty);
  print(mapData.isEmpty);
  print(mapData.runtimeType);
  print(mapData.hashCode);
}

Output :

{King: Arthur, Queen: Alizabeth, Prince: Harry}
3
(King, Queen, Prince)
(Arthur, Alizabeth, Harry)
true
false
JsLinkedHashMap
540333345

Map Common Methods

For ex :

main(){
  var mapData=new Map<int,String>();
  var mapData2={1:"A",2:"B",3:"C"};
  mapData[101]="Good";
  mapData[102]="Very Good";
  mapData[103]="Best";
  mapData[104]="Smarter";
  print(mapData);

  print(mapData.containsKey(111));
  print(mapData.containsValue("Best"));
  print(mapData.remove(104));
  print(mapData.toString());
  
  mapData.clear();
  mapData.addAll(mapData2);
  print(mapData);
  
  mapData.putIfAbsent(105, ()=>"hello");
  print(mapData);
}

Output :

{101: Good, 102: Very Good, 103: Best, 104: Smarter}
false
true
Smarter
{101: Good, 102: Very Good, 103: Best}
{1: A, 2: B, 3: C}
{1: A, 2: B, 3: C, 105: hello}

This all methods and properties describes that dart maps are very handy and dynamic data collection. So, user can anonymously use dart map for storing data in key-value pair.

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 Lists

From, now on we are gonna discuss about the data structures(as name suggests structures used for manipulating different data).

I think, there are 2 data structures a programmer must learn for manipulating and storing the data which are List and HashMap.

So, in this tutorial we are gonna talk in deep about the list data structure.

List is also the built in data type for dart programming language.

Lists is the very common data structure used in almost all of the languages.

Lists is the very handy way to manage data of different objects.

List is the collection of ordered or group of objects of the same data type in general.

In dart, arrays are not used. Instead Arrays will act as the List Objects.

Even dart virtual machine predicts the list as the array objects.

The basic list structure can be described as follow:

For ex :

var list = [10, 20, 30]; // list with only 3 Elements

Above example has 3 list elements 10, 20, 30.

List has the zero based index, which means above list has value 10 at the index 0, value 20 at the index 1 and value 30 at the index 2.

So, which means particular values stored in the list are elements.

While, each elements stored in the particular position in the list is Index.

and therefore, size of the list = [size of the elements] – 1
and size of the list = [size of the last index] // as we know that index starts from 0 to expand up to [total elements-1]

List Syntax :

var list_name=new List(list_size);

With above syntax, fixed size list can be created and we can store data elements up to the specified list size.

we cannot shrink or expand the list size.

List Initialisation :

list_name[index]=value;

the List initialisation is used to assign the values to the list elements.

For ex :

void main()
	{
		var avengers=new List(3);
  		avengers[0]="Hulk";
  		avengers[1]="Thor";
  		avengers[2]="Ironman";
  		print(avengers);
	}

Output :

[Hulk, Thor, Ironman]

The size of the above list is 3 if you try to add 4th element in the list it wiil give you ( Index out of range) exception.

We can also initialise the list at the time of declaration as following :

For ex :

void main(){ 
    var player_list = ["Roger","Rafael","Novak"];    			 
    print(player_list); 		
}

Output :

[Roger, Rafael, Novak]

we can also, create the dynamic list with no specified size. in which, we can add the elements in the list according to our neeeds using add() function defined in List class.

For ex :

void main() { 
   	var languages = new List(); 
   	languages.add("C"); 
	languages.add("Dart");
  	languages.add("Java");
 	print(languages); 
}

Output :

[C, Dart, Java]

List creates an unspecifeid length list using the empty List() Constructor from the List Class.

Lists class have many pre-defined properties and functions to perform efficient tasks for manipulating the data inside the List Structure.

you can also store the data of group of objects with different data types like, String, boolean, integer etc.

For ex :

void main() { 
   	var dataList = new List(); 
   	dataList.add("Toastguyz"); 
   	dataList.add(true);
   	dataList.add(123456);
   	print(dataList); 
}

Output :

[Toastguyz, true, 123456]

List Common Properties

For ex :

main() {
  var list=new List<String>();
  list.add("Sachin");
  list.add("Sehwag");
  list.add("Dhoni");
  list.add("Kohli");
  list.add("rohit");

  print(list.length);
  print(list.reversed);
  print(list.first);
  print(list.hashCode);
  print(list.isEmpty);
  print(list.isNotEmpty);
  print(list.iterator);
  print(list.last);
  print(list.runtimeType);
}

Output :

5
(rohit, Kohli, Dhoni, Sehwag, Sachin)
Sachin
42153199
false
true
Instance of ‘ListIterator’
rohit
List<String>

List Common Methods

For ex :

main() {
  var listValues = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009];
  var list = new List<int>();
  list.add(107);
  list.add(108);
  list.add(109);
  list.add(110);
  list.add(101);
  list.add(102);
  list.add(103);
  list.add(104);
  list.add(105);

  list.removeLast();
  print(list);

  list.sort();
  print(list);

  list.insert(6, 106);
  print(list);

  list.setRange(2, 7, listValues);
  print(list);

  list.remove(110);
  print(list);

  list.asMap();
  print(list);

  print(list.indexOf(109));
  print(list.sublist(3));
  print(list.contains(2004));
  print(list.skip(5));
  print(list.elementAt(2));

  list.addAll(listValues);
  print(list);

  list.shuffle();
  print(list);

  //  print(list.clear());
}

Output :

[107, 108, 109, 110, 101, 102, 103, 104]
[101, 102, 103, 104, 107, 108, 109, 110]
[101, 102, 103, 104, 107, 108, 106, 109, 110]
[101, 102, 2001, 2002, 2003, 2004, 2005, 109, 110]
[101, 102, 2001, 2002, 2003, 2004, 2005, 109]
[101, 102, 2001, 2002, 2003, 2004, 2005, 109]
7
[2002, 2003, 2004, 2005, 109]
true
(2004, 2005, 109)
2001
[101, 102, 2001, 2002, 2003, 2004, 2005, 109, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009]
[2005, 2003, 2001, 101, 2003, 2002, 2004, 2008, 2006, 2007, 109, 2002, 2001, 2005, 2009, 2004, 102]

Again, I must say that list is the important topic to have grip on it. so, make more and more practice with lists to be a better Programmer.

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 Boolean

Booleans are the data types which can have only 2 values true and false.

Now, you’ll think how a data type with only 2 values can be so useful in programming logic.

But, you will know that Booleans are so useful to test any conditional expression.

For ex :

do you want to go to School? //It can have only 2 values ‘Yes’ or ‘No’.

So, similarly Boolean data type uses true and false values which acts as the conditional results for different situations.

To declare any variable as Boolean, bool keyword is used.

For ex :

void main()
{
  bool value;
  print(value);
}

Default value for booleans is null.

You can directly provide the values to boolean variables like,

For ex :

void main()
{
  bool value=false;
  print(value);
}

Similarly we can use booleans for testing different situations according to our logic.

For ex :

void main()
{
  	int A=10,B=20;
	if(A>B)	// conditional expression a>b can be true or false only.
	{	
		print("A is greater than B");
	}else{
		print("B is greater than A");
	}
}

As booleans can have only true or false values. General purpose usage of boolean data type is to evaluate the conditional expressions.

So, if A>B is true then condition satisfies and your program execution enters inside if branch, otherwise program execution moves to else branch.

So, in this way you can Implement Boolean data type anywhere in the programming code to check conditional expressions.

Practice with so many conditional Program definitions to be more familiar with the Booleans.

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 Strings

A data type String is a sequence of UTF-16 code units.

Data type String is the representation of sequence of characters.

Data type String is used for storing values other than numbers like words, sentences etc. in variable.

To declare any varible as String, “String” keyword is used.

You can represent String with words or sententences or quotes in between the single or double quotes.

For ex :

String variableName=”Toastguyz”;
String variableName=’Toastguyz’;

But, dart also provide facility for declaring String variable values in between n number of starting quotes and n number of ending quotes.

For ex :

String variableName=””ToastGuyz””;

You cannot use String variables starting with 4 quotes and ending with 10 quotes for storing the string values.

For ex :

String variableName=””ToastGuyz”””””’; // will generate the compile time error.

We can use string for storing different kind of values like words, sentences or data information etc.

For ex :

void main(){
	String name="ToastGuyz";
	String hobbies="I Love Coding";
	String sarcasm="Are you Smart?";

	print(name);
}

String Manipulation

You can add/append one String value to another String value to generate a new String is termed as Concatenation(Interpolation).

To concatenate one String to another +(plus) operator is used.

For ex :

void main(){
	String firstName="Bill";
	String lastName="Gates";

	print("Name = " + firstName + lastName);
}

Therefore, string manipulation can be helpful to format the String data in appropriate manner as well as for individual needs.

We can use ‘$’ identifier for dynamically change the value of the expression within Strings.

For ex :

void main()
{
		int value=10;
		print("My Favourite Number is $value");
}

Output :

My Favourite Number is 10

You can also manipulate the expression within Strings using ‘${expression}’

So using ‘${}’ identifier we can also manipulate the expression in very neat and handy manner.

For ex :

void main()
{
	int a=10;
  	int b=20;
	print("Total of the Sum is ${a+b} ");
}

Output :

Total of the Sum is 30

Users can also manipulate the 2 string variables in between the expressions like,

For ex :

void main()
{
    		String a='Strongest';
    		String b='Avenger';
    		print("Hulk is the ${a+b}.");
}

Output :

Hulk is the StrongestAvenger.

Manipulating strings in different ways using your logic is fun.

String Common Properties

For ex :

void main()
{
		String a='Strongest';
  
  		print(a.length);
  		print(a.codeUnits);
  		print(a.runes);
  		print(a.runtimeType);
  		print(a.isEmpty);
  		print(a.isNotEmpty);
}

Output :

9
[83, 116, 114, 111, 110, 103, 101, 115, 116]
(83, 116, 114, 111, 110, 103, 101, 115, 116)
String
false
true

String Common Methods

For ex :

void main()
{
	String a='Strongest';
  	String b="Avenger";
  	String c="ABCDEF";
  	String d="abcdef";
        String e="  ab cdefghi ";
  	String f="def";
  	String g="dek";
  
  	print(a.substring(2,5));
  	print(a.codeUnitAt(5));
  	print(a.startsWith("Str"));
  	print(a.replaceAll("ron","toytoy"));
  	print(a.split("n"));
  	print(a.contains("ron"));
  	print(a.indexOf("r"));
  	print(c.toLowerCase());
  	print(d.toUpperCase());
  	print(e.trim());
        print(a.endsWith("est"));
  	print(f.compareTo(g));
  	print(a.toString());
}

Output :

ron
103
true
Sttoytoygest
[Stro, gest]
true
2
abcdef
ABCDEF
ab cdefghi
true
-1
Strongest

In this way, different built-in properties and methods of String data type makes it easy and efficient for performing some handy work.

So practice the String data types with more and more programming definitions to get grip on it.

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 Numbers

Dart Number is the Super type(parent) of the integer and double.

Starting with the first data type numbers, which is divided in to 2 types,

  1. Integer
  2. Double

Numbers can have value from -2^63 to 2^3-1 but as we all know that Dart is converted to javascript directly so, it allows only values in range from -2^53 to 2^53-1. Beyond this range Dart VM will give you a garbage value.

For ex :

Numbers can be 1,-5,3.5,-45.25 etc. So, In this tutorial we will briefly discuss about integer as well as doubles.

Integer

Integer contains all the numbers which does not have decimal values.

You cannot assign the decimal value(fractional value) to an integer data type variable. Dart VM will give you a compile time error if you do so.

Integer variable cannot have values larger than 64 bits. Dart has integer data type range from (-2^63) to (2^63-1) (i.e,-9223372036854775808 to +9223372036854775807) which means you cannot assign the value beyond this range(-2^63 to 2^63-1) to the variable. By, assigning value beyond this range Dart VM will you give you compile time error.

To declare any varible as integrer, int keyword is used.

For ex :

int variableName=7;

User can also provide hex values to the integer variables. which is used to store different color codes.

For ex :

int hex = 0xABCDEF;

User can also perform bitwise shift(<<,>>) ,AND(&) and OR(|) operators. we will briefly discuss about it later.

For ex :

print(3<<6); // which gives value 192

Double

64-bit (double-precision) floating-point numbers, as specified by the IEEE 754 standard.

Integer cannot have fractional(decimal) values. so, double is introduced to achieve the desired requirements.

To declare any variable as Double, double keyword is used.

For ex :

double variableName = 7.7;

User can also store exponential values to the integer variables. which is used to store different color codes.

For ex :

double value= 1.42e5; // value=142000
where, e is the 10 base to power 5

User can perform basic arithmatic operations(+,-,*,/) with the Number data types(int and double included).

The operations performed using either int or double data type can also be performed using num data type as Number is the SuperClass for int and double.

Parsing Numbers

The parse() static function is used to get the number values(either int or double) stored in String variable.

For ex :

void main() {
  String i='10';
  print(num.parse(i)); 
  print(num.parse('10.10')); 
}

User cannot parse any string variables with values other than numeric values.

Number Common Properties

For ex :

void main() {
  int x1=556;
  int x2=-200;
  double y1=121.6;
  double y2=-1000.45;
  
  print(x1.isEven);
  print(x1.isOdd);
  
  print(x1.hashCode);
  print(y1.hashCode);
  
  print(x1.bitLength);
  
  print(x1.isFinite);
  print(y1.isFinite);
  
  print(x1.isInfinite);
  print(y1.isInfinite);
  
  print(x1.isNaN);
  print(y1.isNaN);
  
  print(x1.isNegative);
  print(y1.isNegative);
  
  print(x1.runtimeType);
  print(y1.runtimeType);
  
  print(x2.sign);
  print(y2.sign);
  
}

Output :

[true, false, 556, 121, 10, true, true, false, false, false, false, false, false, int, double, -1, -1]

Number Common Methods

For ex :

void main() {
  int x1=556;
  int x2=200;
  int x3=-9999;
  double y1=121.6;
  double y2=1000.45;
  double y3=-6666.66;
  
  print(x1.toString());
  print(y1.toString());
  
  print(x1.toRadixString(5));
  
  print(x3.abs());
  print(y3.abs());
  
  print(x3.toUnsigned(3));
  print(x3.toSigned(2));
  
  print(x1.round());
  print(y1.round());
  
  print(x1.floor());
  print(y1.floor());
  
  print(x1.ceil());
  print(x2.ceilToDouble());
  print(y1.ceil());
  print(y2.ceilToDouble());

  print(x1.compareTo(x2));
  print(y1.compareTo(y2));
  
  print(x1.gcd(x2));
  
  print(x1.remainder(x2));
  print(y1.remainder(y2));
  
  print(x1.toDouble());
  print(y1.toInt());
  
}

Output :

[4211, 556, 121.6, 9999, 6666.66, 1, 1, 556, 122, 556, 121, 556, 200, 122, 1001, 1, -1, 4, 156, 121.6, 556, 121]

So, we can apply Numbers in many ways ,either as int or double to achieve our desired requirements. Further, we will discuss about Strings in Dart.

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 Variable Scope

The scope of variables is the lifetime of the variable.

The variable scope is the lifetime of a variable for which a particular block of code is executed.

Variable scope can be decided using the type of variables,

  1. Local Variable
  2. Global Variable

Local Variable

A local variable is a type of variable declared inside programming blocks(i.e., for loop, if else, switch and many more) or functions.

It can only be used inside that particular code of block or function in which it is declared or defined.

Once that particular code of block or functions is executed, the scope of a variable is finished or say that the local variable is destroyed.

For Ex :

void main()
{
       int x=1;
       for(int i=0;i<2;i++)
       {
    	 print(i);
	 x++;
	 print(x);
       }
}

Output :

0213

In above example, the scope of variable i is limited inside the loop only. As it is defined inside the loop. As the loop execution completes the scope of variable i get finished.

Similarly, the scope of variable x is limited to only the main function execution. As the execution of main function completes, the lifecycle or scope of the variable finishes and variable gets destroyed as well.

So, the scope of local variable is limited to the block of code under which it is declared or defined whether it ls a function, a loop , a parameter or a block of code.

Global Variable

Global variables are defined outside the function and used to access from anywhere.

The scope of global variable is limited from the start of the program to the end of the program.

For ex :

class Sample
{
  int id=1;
  String name="toastguyz";
  test()
  {
    print("Sample "+id.toString());
  }
}
// global variable
int a=10;
void main()
{
	for(int i=0;i<2;i++)
        {
            print(i);
            print(a);
        }
  Sample S=new Sample();
  S.test();
}

Output :

0
10
1
10
Sample 1

In the above example, the scope of the global variable is from the beginning of the program to the end of the program. While the scope of the local variable i is limited to the end of the execution of the for a loop.

One other example of global variables are instance variables.

Instance variables are the variables declared inside the class but outside the method.

We have discussed about it prior. Checkout our tutorial on instance variable to get familiar with it.

Instance variable acts as global variable for the object of the particular class. The scope of the instance variable starts from the creation of the object and ends with the object destruction.

In the above example, instance variables id and name can be accessed globally for the object S in the class Sample.

So, a local variable is used whenever they need to manipulated inside a block of code only while global variables are used whenever the necessity to access the variable from anywhere in the program is required.

As local variables get destroyed as soon as the block of code gets executed while global variables will obtain the memory till the end of the program. So, both types of variables have their own specific purpose to use. So prefer to use a local variable in general wherever it is possible for memory efficiency. Because a single global variable requires a greater amount of memory in comparison to a local variable

It will be useful to understand the local and global variable usage to become a better developer.

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 Variables

Variables are one of the most important concepts in the programming languages.

They are named memory spaces or temporary assignments for storing values in the program.

The name provided to the variable is known as identifiers.

For ex :

int A=5;

Here, A is a variable storing the reference to the int object with value 5. and A is also the identifier name provided to the variable to be recognized.

Variable Naming Convention Rules

We can assign any name to our variables following some predefined naming convention rules as below,

  • Variable names can contain Alphabets and Numbers.
  • Variable names cannot start with Numbers.
  • They cannot contain spaces and special Characters except dollar ($) and underscore (_) sign.
  • They cannot be the same as reserved keywords like if, for, switch, etc.

Why do we have to follow the naming convention rules?

As we all know that compiler or interpreter can compute or manipulate data much faster than humans. but, they don’t have the capability to think on their own. so, if you assign your variable name as reserved keyword like,

For ex:

int for=0;

So, the compiler will not be able to differentiate between the variable name for and for loop. So to resolve the confliction/ambiguity there are certain rules predefined for naming an identifier.

So, here is the list of predefined keywords which cannot be used as variable names are as following

abstractelseimportsuper
asenuminswitch
assertexportinterfacesync
asyncextendsisthis
awaitextensionlibrarythrow
breakexternalmixintrue
casefactorynewtry
catchfalsenulltypedef
classfinalonvar
constfinallyoperatorvoid
continueforpartwhile
covariantFunctionrethrowwith
defaultgetreturnyield
deferredhidesetdo
ifshowdynamicimplements
static

Variable Syntax

A variable must be declared before it is used in Program.

var the keyword is used for declaring the variable data type dynamically in dart or you can also declare specific data type before the variable name to assign the value.

For ex :

var variableName=”Shiva”;

Var is the best way to declare a variable without specifying its data type.

All variables in dart stores references to the objects or values.

For ex :

int number=10;

Here variable stores the reference(address in memory) to the identifier number containing value 10.

Most of the Languages Supports Type Checking by prefixing the data type with variable name. Type Checking ensures that variables declared with specific data type stores only the values to that specific data type.

For ex :

String name=”Billy”;

Here variable name can contain only String data type values. user cannot assign int or boolean value to String data type variables.

So by prefixing var keyword user do not have to define the data type for the variable. variable will predict the data type which type of data is assigned to variable.

For ex :

var x = 10;

Now x will act as the Int data type and it will have all the properties and methods of Int data type. var y=”hi” similarly, here y will act as the String data type and it will have all the properties and methods of String data type.

So var keyword is used when you do not know which kind of data will be stored in the data type. So at the time of variable declaration using var keyword will help you to get dynamic data type at runtime.

Initial Values

Variables declared but not initialized in dart have initial values null.

For ex :

void main()
{
	var a;
	int b;
	boolean c;
	print(a);
	print(b);
	print(c);
}

Output :

null
null
null

Final Variable

Final variable is the variables which should be initialized at the time of variable declaration.

The value of the final variable can be set only once. we cannot change the value of the final variable at any time.

The final variable doesn’t have any default value. So, the final variable must be Initialized.

When you use a final variable you do not need to define the data type of the variable. final will act as the data type which is assigned to variable.

For ex :

void main()
{
  final value="Hi";
  final value2=101;
  print(value);
  print(value2);
}

Output :

Hi
101

Const Variable

Constant variable is used to store the constant value in the variable.

It must be initialised at the time of declaration.

Also the value of the const variable can be set only once. we can’t change the value of const variable at any time.

The const variable doesn’t have any default value. so, the const variable must be Initialised.

When you use const variable you do not need to define the data type of the variable. const will act as the data type which is assigned to variable.

For ex :

void main()
{
  const value="Hello";
  const value2=102;
  print(value);
  print(value2);
}

Output :

Hello
102

The only difference between final and const is that we can assign the final variable any other value while const variable can have only constant variable. You cannot assign any other value to it.

For ex :

void main()
{
  for(int i=0;i<10;i++)
  {
    final value=i;
    print(value);
  }
}

Output :

0123456789

For ex :

void main()
{
     final i=0;
     const value=i;
     print(value);
}

It will give you a compile time error. because constant can have only compile time values (i.e., values assigned at the time of variable declaration). You cannot assign any value that can change at run time.

So these are the different usages of variables.

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 Data Types

Data type in any language is a classification of data which tells the compiler or interpreter how the programmer wish to use data.

Data types are used generally in type safe languages (Type safety is the concept of preventing type errors while accessing different kinds of data types based on authority of access).

Dart 1.X used optionally type checking while Dart 2.X uses a combination of static type checking and runtime checks to ensure that a variable’s value always matches the variable’s static type.

The Dart supports following built in data types:

  • Numbers
  • Strings
  • Booleans
  • Lists
  • Maps

Numbers

Dart number has 2 subtypes,

  1. Integer
  2. Double

int

Integer data type can have any value from natural numbers and their negative counterparts(i.e., …-3,-2,-1,0,1,2,3,…)

int keyword is used to declare integer data type variable.

For ex :

int a = 7;

double

Integer data type cannot accept decimal values so, double data type is Introduced with 64 bit range which accepts all the decimal values from range …-3,-2,-1,0,1,2,3,…

double keyword is used to declare double data type variable.

For ex:

double a = 7.7;

Strings

Strings are nothing but sequence of characters or bunch of characters. It can be used to store any number of characters like, for storing name, personal details, different kind of information etc.

String keyword is used to declare string data type variable.

For ex :

String a = “Ram”;

Boolean

Boolean data type is used whenever we want to apply conditional test on our logic. It can have only two values True or false.

bool keyword is used to declare boolean data type variable.

For ex :

bool x = 2>3; // so, x has value false.

Lists

list is nothing but the collection of different elements of the same type or collection of ordered group of objects.

So, list is used to store elements of particular kind of data type or to store objects.

In dart arrays are not used. instead dart uses arrays as list-objects.

For ex :

void main(){
	List<int> a=new List();  // int is  type of data
	a=[1,2,3,4,5];
	print(a);
} 

Output :

[1,2,3,4,5]

Maps

Maps is one of the best data Structure for storing the data in key-value pairs.

Each key is associated with one value in Maps. Both keys and values can be of any type for mapping.

For ex :

void main(){
	Map<String,String> a=new Map();
  	a={'Username':'BillGates','Password':'123456'};
 	print(a);}

Output :

{Username: BillGates, Password: 123456}

Dynamic Keyword

As we all know that dart is optionally typed language which means statically typed as well as dynamically typed language.

Statically typed language is one in which the data type of the variables or parameters are defined at the time of compilation or say declaration.

For ex :

String, Boolean, Map etc.

While Dynamically typed language is one in which the data type of the variables or parameters are defined at runtime. So, dart has dynamic keyword for declaring variable data type at runtime.

For ex :

void main()
{
    dynamic x=5;            // x will be evaluated at runtime as integer variable having value 5.
    dynamic y="Toastguyz";  // y will be evaluated at runtime as String variable having value "Toastguyz".
    dynamic z=true;         // z will be evaluated at runtime as boolean variable having value true.
    print(x);
    print(y);
    print(z);
}

Output :

5
Toastguyz
true

In this way, If you’re are not sure about the type of variable you can declare it as dynamic which will be explicitly evaluated based on value assigned to it.

So, these are the basics of for each data types. You must deep dive in to dart data types to quickly grasp the 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 Syntax

For every programming language, there are certain rules are predefined for writing programs.

Dart also have its own syntax or structure for writing programs

A program written in dart may be consist of

  • Operator
  • Variables
  • Functions
  • Expressions
  • Class
  • Objects
  • Constructors
  • Libraries
  • Typedef
  • Data Structures represented as Collections/Generics
  • Comments

We will understand each and every topic of dart through step by step to have command over dart language and smoother our experience of learning dart syntax.

Let’s have a basic hello world example in dart,

Helloworld.dart file

main() {
print(“Hello World”);
}

In Dart, The execution of your program starts with main() function. main() is the entry point function which is mandatory in a dart program.

Any dart code written in a file must have extension have “.dart”. In above example, we have created a new file named as Helloworld with .dart extension and written our program inside it.

With the .dart extension file we can identify that the particular file has code written in the dart language.

Similarly, there are other syntactical concepts or rules that will help you to understand the dart syntax easily.

Let’s have intro with each dart syntactical rules one by one.

White-spaces and Line Breaks

We can freely use white-spaces, tabs and new lines as much as we want in our programs and we are able to format our code because Dart ignores spaces, tabs and newlines that appear in code.

Dart is case sensitive

Dart is case sensitive language, so it differentiates lowercase and uppercase characters in your program.

Statements ends with a semicolon

In dart code, every statement must end with semicolon (;). We can write multiple statements in a single line, but we need to add semicolon between them.

Comments in Dart

Comments are useful for any program. It improves readability of our program. They are used to notate the particular code-block or function or class is used for what purpose or helps other programmers to understand our code by reading comments.

In dart, two types of comment are there:

  • Single Line Comment : Any text between // is comment.
  • Multi Line Comment : Any text between /* */ is multiline comment.

For ex :

// This is example of single line comment.

/* Line 1
Line 2 –>This is example of multiline comment.
Line 3 */

Dart syntax is conventional programming syntax like C, C++ and java. Hence, easier to learn and understand. So, you can have command over the dart language in very short time. So, make yourself ready to have a smoother journey for learning an object oriented dart programming 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.