Starting with Dart
2 Datatypes in Dart
2.1 Numbers
-
int: The
intdata type is used to represent whole numbers. Syntax:int var_name; -
double: The
doubledata type is used to represent 64-bit floating-point numbers. Syntax:double var_name; -
num: The
numtype is an inherited data type of theintanddoubletypes.
void main() {
// declare an integer
int num1 = 2;
// declare a double value
double num2 = 1.5;
// print the values
print(num1);
print(num2);
}
The parse() function is used parsing a string containing numeric literal and convert to the number.
void main()
{
var a1 = num.parse("1");
var b1 = num.parse("3.14");
var c1 = a1+b1;
print("Product = ${c1}");
num a2 = num.parse("2");
num b2 = num.parse("2.73");
num c2 = a2+b2;
print("Product = ${c2}");
int a3 = int.parse("3");
double b3 = double.parse("1.6");
num c3 = a3+b3;
print("Product = ${c3}");
}
Some methods:
-
abs(): This method gives the absolute value of the given number.
-
ceil(): This method gives the ceiling value of the given number.
-
floor(): This method gives the floor value of the given number.
-
compareTo(): This method compares the value with other numbers.
-
remainder(): This method gives the truncated remainder after dividing the two numbers.
-
round(): This method returns the round of the number.
-
toDouble(): This method gives the double equivalent representation of the number.
-
toInt(): This method returns the integer equivalent representation of the number.
-
toString(): This method returns the String equivalent representation of the number
-
truncate(): This method returns the integer after discarding fraction digits.
2.2 Strings
Strings can be defined usinge either single or double quotes, e.g. String str = "I love food"; and String str = ’I love
food’;.
You can put the value of an expression inside a string by using $expression. This is called interpolation. Strings can also be concatenated using +.
void main()
{
String str1 = 'dart';
String str2 = 'c';
// interpolation
print ("I prefer $str1 to $str2.");
// concatenation
print ("I prefer " + str1 + " to " + str2 + ".");
}
2.3 Lists
In Dart programming, the List data type is similar to arrays in other programming languages. List is used to representing a collection of objects. It is an ordered group of objects.
void main()
{
List<String> fruits = ["apple", "orange", "banana"];
var vegetables = ["potato", "onion"];
// Printing all the values in List
print("fruits = $fruits.");
print("vegetables = $vegetables.");
// Adding new value in List and printing it
fruits.add("pineapple");
print("fruits = $fruits.");
// Adding multiple values
vegetables.addAll(["carrot", "lettuce"]);
print("vegetables = $vegetables.");
// Insert at a specific index
fruits.insert(2, 'kiwi');
print("fruits = $fruits.");
// Insert many at a specific index
fruits.insertAll(1, ['melon', 'peach']);
print("fruits = $fruits.");
// Remove item
fruits.remove("banana");
print("fruits = $fruits.");
// Remove item at index
fruits.removeAt(3);
print("fruits = $fruits.");
// Remove all
fruits.clear();
print("fruits = $fruits.");
// Multidimentional Lists
List<List<String>> table = [];
List<String> row1 = ["item11", "item12"];
List<String> row2 = ["item21", "item22"];
List<String> row3 = ["item23", "item23"];
table.add(row1);
table.add(row2);
table.add(row3);
print("table = $table.");
table[0].remove("item11");
print("table = $table.");
List<List<List<String>>> hyperTable = [];
hyperTable.addAll([table, [["item31", "item32"],["item41", "item42"]]]);
print("hyperTable = $hyperTable.");
}
3 Control Flow in Dart
Decision-making statements are those statements that allow the programmers to decide which statement should run in different conditions.
3.1 Conditional Statements
3.1.1 If Statement
There are four ways to achieve this:
-
if Statement
-
if-else Statement
-
else-if Ladder
-
Nested if Statement
void main()
{
int val = 10;
if (val < 9)
{
print("Condition 1 is true");
val++;
}
else if (val < 10)
{
print("Condition 2 is true");
}
else if (val >= 10)
{
print("Condition 3 is true");
}
else
{
print("All the conditions are false");
}
}
3.1.2 Switch Statement
Switch-case statements are a simplified version of the nested if-else statements. Its approach is the same as that in Java. Rules to follow in switch case:
-
There can be any number of cases. But values should not be repeated.
-
The case statements can include only constants. It should not be a variable or an expression.
-
There should be a flow control i.e break within cases. If it is omitted than it will show error.
-
The default case is optional.
-
Nested switch is also there thus you can have switch inside switch.
void main()
{
int val = 1;
switch (val)
{
case 1:
{
print("GeeksforGeeks number 1");
} break;
case 2:
{
print("GeeksforGeeks number 2");
} break;
case 3:
{
print("GeeksforGeeks number 3");
} break;
default:
{
print("This is default case");
} break;
}
}
3.2 Loop Statements
A looping statement in Dart or any other programming language is used to repeat a particular set of commands until certain conditions are not completed. There are different ways to do so. They are:
-
for loop
-
for… in loop
-
for each loop
-
while loop
-
do-while loop
3.2.1 for loop
void main()
{
for (int i = 0; i < 5; i++)
{
print('Hello!');
}
}
3.2.2 for .. in loop
void main()
{
var list = [ 1, 2, 3, 4, 5 ];
for (int i in list)
{
print(i);
}
}
3.2.3 for each ... loop
void main()
{
var list = [1,2,3,4,5];
list.forEach((var num)=> print(num));
}
3.2.4 while loop
void main()
{
var val = 4;
int i = 1;
while (i <= val)
{
print('Hello!');
i++;
}
}
3.2.5 do .. while loop
void main()
{
var val = 4;
int i = 1;
do
{
print('Hello!');
i++;
} while (i <= val);
}
3.2.6 Break Statement
This statement is used to break the flow of control of the loop i.e if it is used within a loop then it will terminate the loop whenever encountered. It will bring the flow of control out of the nearest loop.
void main()
{
int count = 1;
while (count <= 10)
{
print("You are inside loop $count");
count++;
if (count == 4)
{
break;
}
}
print("You are out of while loop");
}
3.2.7 Continue Statement
While the break is used to end the flow of control, continue on the other hand is used to continue the flow of control. When a continue statement is encountered in a loop it doesn’t terminate the loop but rather jump the flow to next iteration.
void main()
{
int count = 0;
while (count <= 10)
{
count++;
if (count == 4)
{
print("Number 4 is skipped");
continue;
}
print("You are inside loop $count");
}
print("You are out of while loop");
}
4 Functions
The function has the following.
-
function_name: defines the name of the function.
-
return_type: defines the datatype in which output is going to come.
-
return value: defines the value to be returned from the function.
int add(int a, int b)
{
// Creating function
int result = a + b;
// returning value result
return result;
}
void main(){
// Calling the function
var output = add(10, 20);
// Printing output
print(output);
}
Dart allows functions with optional parameters, and lambda functions or arrow functions. But you should note that with lambda functions you can return value for only one expression.
5 Classes + Summary
import "dart:collection";
import "dart:math" as math;
void main()
{
// Single line comment
/**
* Multi-line comment
* Can comment several lines
*/
/// Code doc comment
/// It uses markdown syntax to generate code docs when making an API.
/// Code doc comment is the recommended choice when documenting your APIs, classes and methods.
/// Constants are variables that are immutable cannot be change or altered.
const myConst = "I CANNOT CHANGE";
myConst = "DID I?"; //Error
/// Final is another variable declaration that cannot be change once it has been instantiated. Commonly used in classes and functions
/// `final` can be declared in pascalCase.
final myVar = "value cannot be changed once instantiated";
myVar = "Seems not"; //Error
/// `var` is another variable declaration that is mutable and can change its value. Dart will infer types and will not change its data type
var myVar = "Variable string";
myVar = "this is valid";
myVar = false; // Error.
/// `dynamic` is another variable declaration in which the type is not evaluated by the dart static type checking.
/// It can change its value and data type.
dynamic myVar = "I'm a string";
myVar = false; // false
/// Functions can be declared in a global space
/// Function declaration and method declaration look the same.
/// Dart will execute a function called `main()` anywhere in the dart project.
myFun1()
{
myFun2();
}
myFun2()
{
// ...
}
/// Functions have closure access to outer variables.
/// In this example dart knows that this variable is a String.
var myVar = "An external variable";
fun3()
{
print(myVar);
}
/// Class declaration takes the form of class name { [classBody] }.
/// Where classBody can include instance methods and variables, but also
/// class methods and variables.
class MyClass
{
String myVar1 = "I am a public variable";
String _myVar2 = "I am a private variable"; // to a file
MyClass(String myVar1, String myVar2)
{
this.myVar1 = myVar1;
this._myVar2 = myVar2;
}
String getVar1()
{
return myVar1;
}
String get getVar1Ugly
{
return myVar1;
}
void setVar1(String someVar)
{
this.myVar1 = someVar;
}
void set setVar1Ugly(String someVar)
{
this.myVar1 = someVar;
}
}
main()
{
MyClass myClass = new MyClass("1", "2");
print("myClass.myVar1 = ${myClass.getVar1Ugly}");
myClass.setVar1Ugly = "5";
print("myClass.myVar1 = ${myClass.getVar1Ugly}");
}
/// Inheritance
// Base class
class Animal {
String name = "";
// Constructor
Animal(String name)
{
this.name = name;
}
// Method in the base class
void makeSound()
{
print('$name makes a sound.');
}
}
// Derived class Cat
class Cat extends Animal {
Cat(String name) : super(name); // Passing name to the Animal constructor
// Overriding the makeSound method
@override
void makeSound()
{
print('$name says Meow.');
}
}
// Derived class Dog
class Dog extends Animal {
Dog(String name) : super(name); // Passing name to the Animal constructor
// Overriding the makeSound method
@override
void makeSound()
{
print('$name says Woof.');
}
}
void main() {
// Creating an instance of Cat
Cat cat = Cat('Tom');
cat.makeSound(); // Output: Tom says Meow.
// Creating an instance of Dog
Dog dog = Dog('Spike');
dog.makeSound(); // Output: Spike says Woof.
}
/// Loops in Dart take the form of standard for () {} or while () {} loops,
String myList = ["a", "b"];
main()
{
for (int i = 0; i < myList.length; i++)
{
print("${myList[i]}");
}
int i = 0;
while (i < myList.length)
{
print("${myList[i]}");
i++;
}
for (String item in myList)
{
print("$item");
}
myList.forEach((item) => print("${item}"));
}
}