Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

INTRODUCTION TO DART PROGRAMMING and FLUTTER FRAMEWORK

What is Flutter
• released the first version for developers in 2018. Dynamic type variable in Dart:
• an SDK for building fast-moving and engaging cross-platform mobile apps provided by Google. • This is a special variable initialized with keyword dynamic. The variable declared with this data type
• Flutter supports compiling code on both Android and iOS using a single code base written in Dart can store implicitly any value during running the program. It is quite similar to var datatype in Dart,
• Dart is a development language for Flutter apps. but the difference between them is the moment you assign the data to variable with var keyword it
• In 2020, it received enhanced functionality and now can be used to create Flutter web apps and is replaced with the appropriate data type.
Flutter desktop apps (for macOS). Syntax:
• Flutter is a unique cross-platform tool type and does not need intermediate components to connect dynamic variable_name;
to device features such as a camera or Bluetooth.
• This leads to better performance and helps create a great UX. Operators in Dart
• it uses its own user interface components instead of platform-specific ones like UIView in iOS or • The operators are special symbols that are used to carry out certain operations on the operands.
Fragments and ViewGroups in Android. • The Dart has numerous built-in operators which can be used to carry out different functions, for
example, ‘+’ is used to add two operands.
What is DART • Operators are meant to carry operations on one or two operands.
• Dart is an open-source general-purpose programming language developed by Google. It supports
application development in both client and server-side. But it is widely used for the development of Different types of operators in Dart
android apps, iOS apps, IoT(Internet of Things), and web applications using the Flutter Framework. • Arithmetic Operators
• Dart is a dynamic, class-based, object-oriented programming language with closure and lexical • Relational Operators
scope. Syntactically, it is quite similar to Java, C, and JavaScript. • Type Test Operators
• Bitwise Operators
TWO TYPES OF COMPILATION TECHNIQUES. • Assignment Operators
• AOT (Ahead of Time) - It converts the Dart code in the optimized JavaScript code with the help of • Logical Operators
the dar2js compiler and runs on all modern web-browser. It compiles the code at build time. • Conditional Operator
• JIT (Just-In-Time) - It converts the byte code in the machine code (native code), but only code that • Cascade Notation Operator
is necessary.
History Arithmetic Operators
• Dart was revealed for the first time in the GOTO conference in the month of 10th - 12th October
2011 at Aarhus, Denmark. This class of operators
• It is initially designed by the Lars bark and Kespar and developed by Google.
Why Dart? contain those operators
• Dart is a platform-independent language and supports all operating systems such as Windows,
Mac, Linux, etc. which are used to perform
• It is an open-source language, which means it available free for everyone. It comes with a BSD
license and recognized by the ECMA standard. arithmetic operation on the
• It is an object-oriented programming language and supports all features of oops such as
inheritance, interfaces, and optional type features. operands
• Dart is very useful in building real-time applications because of its stability.
• Dart comes with the dar2js compiler which transmits the Dart code into JavaScript code that runs
on all modern web browser.
• The stand-alone Dart VM permits Dart code to run in a command-line interface environment.

Key Points to Remember


Before learning the Dart, we should keep these concepts in mind. These concepts are given below.
• Everything in Dart is treated as an object including, numbers, Boolean, function, etc. like Python.
All objects inherit from the Object class.
• Dart tools can report two types of problems while coding, warnings and errors. Warnings are the
indication that your code may have some problem, but it doesn't interrupt the code's execution,
whereas error can prevent the execution of code.
• Dart supports sound typing.
• Dart supports generic types, like List<int>(a list of integers) or List<dynamic> (a list of objects of
any type).

Dart – Comments
• In every programming language comments play an important role for a better understanding of the
code in the future or by any other programmer. Comments are a set of statements that are not
meant to be executed by the compiler. They provide proper documentation of the code.

Types of Dart Comments:


• Dart Single line Comment. Dart single line comment is used to comment a line until line break
occurs. It is done using a double forward-slash (//).
• Dart Multiline Comment. Dart Multiline comment is used to comment out a whole section of code. It
uses ‘/*’ and ‘*/’ to start and end a multi-line comment respectively.
• Dart Documentation Comment. Dart Documentation Comments are a special type of comment
used to provide references to packages, software, or projects.Dart supports two types of
documentation comments “///”(C# Style) and “/**…..*/”(JavaDoc Style). It is preferred to use “///” for
doc comments as many times * is used to mark list items in a bulleted list which makes it difficult to
read the comments. Doc comments are recommended for writing public APIs.

Dart – Variables
• A variable name is the name assign to the memory location where the user stores the data and
that data can be fetched when required with the help of the variable by calling its variable name.

Variable Declaration:

• To declare a variable:
Syntax: Type Test Operators
type variable_name; • This class of operators contain those operators which are used to perform comparison on the
• To declare multiple variables of same type: operands.
Syntax:
type variable1_name, variable2_name, variable3_name, ....variableN_name;
Conditions to write variable name or identifiers :
• Variable name or identifiers can’t be the keyword.
• Variable name or identifiers can contain alphabets and numbers.
• Variable name or identifiers can’t contain spaces and special characters, except the underscore(_)
and the dollar($) sign.
• Variable name or identifiers can’t begin with number.
Note:
Dart supports type-checking, it means that it checks whether the data type and the data that
variable holds are specific to that data or not.

Type of the variable


• Integer
• Double
• String
• Booleans Assignment Operators
• Lists • This class of operators contain those operators which are used to assign value to the operands.
• Maps

Keywords in Dart:

Logical Operators
• This class of operators contain those operators which are used to logically combine two or more
conditions of the operands
• The number in Dart Programming is the data type that is used to hold the numeric value. Dart
numbers can be classified as:
• The int data type is used to represent whole numbers.
• The double data type is used to represent 64-bit floating-point numbers.
• The num type is an inherited data type of the int and double types.
Example
void main() {
// declare an integer
int num1 = 2;
// declare a double value
double num2 = 1.5;
// print the values
print(num1);
print(num2);
var a1 = num.parse("1");
var b1 = num.parse("2.34");
Conditional Operators
var c1 = a1+b1;
print("Product = ${c1}");
}

String
• It used to represent a sequence of characters. It is a sequence of UTF-16 code units. The keyword
string is used to represent string literals. String values are embedded in either single or double-
quotes.
SAMPLE CODE:
void main() {
String string = ‘Dart Porgramming';
String str = 'Coding is ';
String str1 = 'Fun';
print (string);
print (str + str1);
}
Boolean
Cascade Notation Operators • It represents Boolean values true and false. The keyword bool is used to represent a Boolean
• This class of operators allows you to perform a sequence of operation on the same element. It literal in DART.
allows you to perform multiple methods on the same object. void main() {
String str = 'Coding is ';
String str1 = 'Fun';

bool val = (str==str1);


print (val);
}
Dart – Standard Input Output
• Standard Input in Dart: List
• In Dart programming language, you can take standard input from the user through the console via • List data type is similar to arrays in other programming languages. A list is used to represent a
the use of .readLineSync() function. To take input from the console you need to import a library, collection of objects. It is an ordered group of objects.
named dart:io from libraries of Dart. void main()
• About Stdin Class: {
• This class allows the user to read data from standard input in both synchronous and asynchronous List gfg = new List(3);
ways. The method readLineSync() is one of the methods used to take input from the user gfg[0] = ‘Class';
Example gfg[1] = 'For';
import 'dart:io'; gfg[2] = ‘ITP 324';
void main()
{
print("Enter your name?"); print(gfg); [Class, For, ITP 324]
String? name = stdin.readLineSync(); print(gfg[0]); Class
print("Hello, $name! \nWelcome to ITP 324 Class!"); }
} Map
• The Map object is a key and value pair. Keys and values on a map may be of any type. It is a
Standard Output in Dart dynamic collection.
• In dart, there are two ways to display output in the console: void main() {
• Using print statement. Map gfg = new Map();
• Using stdout.write() statement. gfg['First'] = ‘Class';
Example gfg['Second'] = 'For';
import 'dart:io'; gfg['Third'] = ‘ITP 324';
print(gfg);
}
void main()
{ Dart – Sets
// Printing in first way • Sets in Dart is a special case in List where all the inputs are unique i.e it doesn’t contain any
print("Welcome to ITP 324 Class!”); // printing from print statement repeated input. It can also be interpreted as an unordered array with unique inputs. The set comes
in play when we want to store unique values in a single variable without considering the order of
the inputs. The sets are declared by the use of a set keyword.
// Printing in second way • There are two ways to do so:
stdout.write("Welcome to ITP 324 Class!”); // printing from stdout.write() var variable_name = <variable_type>{};
} or,
import 'dart:io'; Set <variable_type> variable_name = {};
void main()
{ Example
print("-----------Sample DART Source Code-----------"); void main()
print("Enter first number"); {
int? n1 = int.parse(stdin.readLineSync()!); // Declaring set in First Way
var gfg1 = <String>['ITP324 for ITP324'];
// Printing First Set
print("Enter second number"); print("Output of first set: $gfg1");
int? n2 = int.parse(stdin.readLineSync()!); // Declaring set in Second Way
var gfg2 = <String>{"ITP 324", "For", "ITP 324"};
// Printing Second Set
// Adding them and printing them print("Output of second set: $gfg2");
int sum = n1 + n2; }
print("Sum is $sum");
} Example
import 'dart:collection';
Dart – Data Types void main()
{
// Creating a Queue
Queue<String> geek = new Queue<String>();
print(geek);
// Adding elements in a Queue
geek.add("Geeks");
geek.add("For");
geek.add("Geeks");
// Printing the
print(geek);
}
Example with List
import 'dart:collection';
void main()
{
Number
// Creating a List
List<String> geek_list = ["Geeks","For","Geeks"]; • }
// Creating a Queue through a List • }
Queue<String> geek_queue = new Queue<String>.from(geek_list); • }
// Printing the elements in the queue Switch Case in Dart
print(geek_queue); switch-case statements are a simplified version of the nested if-else statements.
} Syntax and FLowchart
switch ( expression ) {
case value1: {
DART - DECISION MAKING STATEMENTS Case Statement 1
Decision-making statements } break;
• Decision-making statements are those statements which allow the programmers to decide which case value2: {
statement should run in different conditions. Case Statement 2
FOUR DECISION MAKING STATEMENTS } break;
1. IF Statement
2. IF Else Statement
3. Else…IF Ladder default: {
4. Nested IF Statement default case statement
} break;
IF STATEMENT }
• This type of statements simply checks the condition and if it is true the statements within it is Nested switch-case statement Example
executed but if it in is not then the statements are simply ignored in the code void main()
IF Statement Syntax and Flowchart {
SYNTAX: int g1 = 6;
if ( condition ){ String g2 = “Section1";
// body of if switch (g1) {
} case 1: {
next statement switch (g2) {
Example Dart Code case ‘Section1': {
void main() print("Welcome to ITP 324 Section 1!");
{ }
int a = 10; }
} break;
case 2: {
if (a > 3) { print(" ITP 324 Section 2");
print("Condition is true"); } break;
} default: {
} print("This is default case");
OUTPUT: } break;
Condition is true }
}
IF Else Statement Dart – Loops
This type of statement simply checks the condition and if it is true, the statements within is executed but if not then • Looping statement in Dart or any other programming language is used to repeat a certain set of
else statements are executed commands until certain conditions are not completed.
IF Else Statement Syntax and Flowchart 1. for loop
Syntax: 2. for… in loop
if ( condition ){ 3. while loop
// body of if 4. do-while loop
}
else { for loop Syntax and Flowchart
// body of else SYNTAX:
} for(initialization; condition; test expression){
Example of Dart Code // Body of the loop
void main() }
{ Control flow goes as:
int g = 10; 1. initialization
if (g > 30) { 2. Condition
print("Condition is true"); 3. Body of loop
} 4. Test expression
else { For Loop Example
print("Condition is false");
}
void main() I i<5
}
{ 0 0<5 - T
OUTPUT:
for (int i = 0; i < 5; i++) { 1 1<5 - T
Condition is false
print(‘Hello!!!’); 2 2<5 - T
else…if Ladder
} 3 3<5 - T
} 4 4<5 - T
• This type of statement simply checks the condition and if it is true the statements within it is
OUTPUT: 5 5<5 - F
executed but if it in is not then other if conditions are checked, if they are true then they are
Hello!!!
executed and if not then the other if conditions are checked. This process is continued until the
Hello!!!
ladder is completed.
Hello!!!
Syntax and Flowchart
Hello!!!
Syntax:
Hello!!!
if ( condition1 ){
for…in loop
Statement 1
• For…in loop in Dart takes an expression or object as an iterator.
}
Syntax:
else if ( condition2 ){
for (var in expression) {
Statement 2
// Body of loop
}
}
else {
For In Loop Example
Statement 3
void main()
}
{
Example Dart Code
var x = [ 1, 2, 3, 4, 5 ];
for (int i in x) {
void main()
print(i);
{
}
int g = 10;
}
if (g < 9) {
1
print("Condition 1 is true");
2
g++;
3
}
4
else if (g < 10) {
5
print("Condition 2 is true");
while loop
}
• The body of the loop will run until and unless the condition is true.
else if (g >= 10) {
print("Condition 3 is true");
} Syntax:
else { while(condition){
print("All the conditions are false"); text expression;
} // Body of loop
} }
Nested if Statement do..while loop
• This type of statements checks the condition and if it is true then the if statement inside it checks • The body of the loop will be executed first and then the condition is tested.
its condition and if it is true then the statements are executed otherwise else statement is
executed.
• Syntax: Syntax:
• if ( condition1 ){ do{
• //statement if true text expression;
• else { // Body of loop
• if ( condition2 ){ }while(condition);
• // Body of if
• } Dart – Loop Control Statements
• Else{ Dart supports two types of loop control statements:
• // Body of else 1. Break Statement
2. Continue Statement }
Break Statement:
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.
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
When a continue statement is encountered in a loop it doesn’t terminate the loop but rather jump the flow to next
loop whenever encountered. It will bring the flow of control out of the nearest loop.
iteration.
Syntax:
Syntax: continue;
Using continue inside while loop
break; void main()
{
int count = 0;
Using break inside while loop while (count <= 10) {
count++;
void main() if (count == 4) {
{ print("Number 4 is skipped");
int count = 1; continue;
}

while (count <= 10) {


print(“Class, you are inside loop $count"); print(“Class, you are inside loop $count");
count++; }

if (count == 4) { print(“Class, you are out of while loop");


break; Using continue inside for loop
} void main()
} {
print(“Class, you are out of while loop"); for (int i = 1; i <= 10; ++i) {
}
Using break inside do..while loop
void main() if (i == 2) {
{ print(“Class, you are inside loop $i");
int count = 1; continue;
}
}
do {
print(“Class, you are inside loop $count");
count++; print(“Class, you are out of loop");
}

if (count == 5) { L3
break; DART – FUNCTIONS
} Function
} while (count <= 10); Function is a set of statements that take inputs, do some specific computation and produces output.
print(“Class, you are out of do..while loop"); Functions are created when certain statements are repeatedly occurring in the program and a function is
} created to replace them.
Using break inside for loop Functions make it easy to divide the complex program into smaller sub-groups and increase the code
void main() reusability of the program.
{ Function Syntax:
for (int i = 1; i <= 10; ++i) { return_type function_name ( parameters ) {
if (i == 2) // Body of function
break; return value;
}
//To call a function
print(“Class, you are inside loop $i"); function_name (argument_list);
} • 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.
print(“Class, you are out of loop"); Example: A dart program that calculates the sum of two numbers.

SOURCE CODE: OUTPUT: void main()


int add(int a, int b) {
30 var output = add(10, 20);
{ print(output);
int result = a + b; }
return result;
}
Recursive Function in Dart

{
print("Welcome to $str1");
The recursive function is those functions in which function calls itself. It is a good way to avoid repeatedly calling the }
same function to get the output.’ }
Object
Example: Recursive function for fibonacci series.
int fibonacci(int n) • An object is an instance of a class.
{ • Objects are allocated memory space whenever they are created.
// This is recursive function as it calls itself • An object is created many times as per requirement.
return n < 2 ? n : (fibonacci(n - 1) + fibonacci(n - 2)); • Objects can be manipulated.
} • Each object has its own values, which are associated with it.
• Objects are like a variable of the class.
Syntax for Object
1 1 2 3 5 8 13 21
void main()
var object_name = new class_name([ arguments ]);
{
new is the keyword use to declare the instance of the class
var i = 8; // input
object_name is the name of the object and its naming is similar to the variable name in dart.
print('fibonacci($i) = ${fibonacci(i)}');
class_name is the name of the class whose instance variable is been created.
}
arguments are the input which are needed to be pass if we are willing to call a constructor.
dot(.) operator
Class
• Used to access the field
• Class is used as a template for declaring and creating the objects.
Syntax:
• When a class is created, no memory is allocated.
// For accessing the property
• The class has to be declared only once.
object_name.property_name;
• A class cannot be manipulated as they are not available in the memory.
// For accessing the method
• It is declared with the class keyword.
object_name.method_name();
• Class does not contain any values which can be associated with the field.
Example
• A class is a blueprint for creating objects (a particular data structure), providing initial values for state
class ite312 {
(member variables or attributes), and implementations of behavior (member functions or methods).
String str1 = "";
Syntax of Class
void itp() {
print("Welcome to $str1");
class class_name { }
// Body of class }
} void main() {
class is the keyword use to initialize the class. // Creating Instance of class
class_name is the name of the class. var itpClass = new ite312();
Body of class consists of fields, constructors, getter and setter methods, etc. itpClass.str1 = "ITE 312 Class for Today!!";
Example itpClass.itp();
class itp324 { }
// Creating Field inside the class Constructors
String str1; • Constructors are a special method that is used to initialize an object when created in the program.
// Creating Function inside class • In object-oriented programming when an object is created, it automatically calls the constructor.
void itp()
• All classes have their default constructor which is created by the compiler when class is called, • There is no need to create a class object to access a static variable or call a static method: simply
moreover one can also define constructor of its own. But, you must note that if you do so then the put the class name before the static variable or method name to use them.
default constructor will not be created and will be ignored. Dart Static Variables
Syntax of a Constructor
• The static variables belong to the class instead of a specific instance. A static variable is common
class_name( [ parameters ] ){ to all instances of a class: this means only a single copy of the static variable is shared among all
// Constructor Body the instances of a class. The memory allocation for static variables happens only once in the class
} area at the time of class loading.
class_name is the name of the class whose constructor is being created.
parameters are optional features and they can and can’t be defined for the constructor. The default constructor has
Declaring Static Variables
no parameter defined in it.
Constructor body is the body of the constructor and is executed when the constructor is called i.e when an object is
created. Syntax:
Constructors don’t have any return type. static [data_type] [variable_name];
Example 1: Creating a constructor in Dart Example:
static var emp_dept;
Full Example
class G{
class Employee {
// Creating Constructor
static var emp_dept; //declaring static variable
G() {
var emp_name;
print('Constructor is being created');
int emp_salary;
}
showDetails() {
String str1;
print("Name of the Employee is: ${emp_name}");
void itp(){
print("Salary of the Employee is: ${emp_salary}");
print("Welcome to $str1");
print("Dept. of the Employee is: ${emp_dept}");
}
}
}
}
Example:
void main() {
Class G{
Employee e1 = new Employee();
// Creating Constructor with parameter
Employee e2 = new Employee();
G(int a) {
Employee.emp_dept = "MIS"; //accessing static variable

print('Constructor is being created');


print("GeeksforGeeks Dart static Keyword Example");
}
e1.emp_name = 'Rahul';
String str1;
e1.emp_salary = 50000;
void itp(){
e1.showDetails();
print("Welcome to $str1");
}
} e2.emp_name = 'Tina';
Parameterized Constructor e2.emp_salary = 55000;
• In Dart, you can also create a constructor having some parameters. These parameters will decide e2.showDetails();
which constructor will be called and which will be not. }
Example: Static Methods
Class G{
// Creating Constructor with parameter
G(int a) { Syntax: Declaring Static Method
static return_type method_name()
{
print('Constructor is being created'); // Statement(s)
} }
String str1; Syntax: Calling Static Method
void itp(){ ClassName.staticMethod();
print("Welcome to $str1");
}
} Example
Named Constructor: class StaticMem {
static int num;
Syntax: static disp() {
class_name.constructor_name ( parameters ){ print(" The value of num is ${StaticMem.num}") ;
// Body of Constructor }
} }
Example: void main() {
Class G{ StaticMem.num = 75;
// Creating Constructor with parameter StaticMem.disp();
G.constructor1(int a) { }
print('Constructor is being created');
}
G.constructor2(int a) { Dart string function
print('Constructor is being created'); Split method
} • Splits the string at matches of pattern and returns a list of substrings.
String str1; Example:
void itp(){ const string = 'Hello world!’;
print("Welcome to $str1"); final splitted = string.split(' ‘);
} print(splitted);
this keyword indexOf method
• This keyword represents an implicit object pointing to the current class object. • Returns the position of the first match of pattern in this string, starting at start, inclusive:
• It refers to the current instance of the class in a method or constructor. Example:
• The this keyword is mainly used to eliminate the ambiguity between class attributes and const string = 'Dartisans';
parameters with the same name. print(string.indexOf('art'));
Uses of this Keyword Substring method
• It can be used to refer to the instance variable of the current class • The substring method returns a substring from the start index (inclusive) to the end index
• It can be used to make or Initiate current class constructor (exclusive):
• It can be passed as an argument in the method call Example:
• It can be passed as an argument in the constructor call String? result = parentString. substring([start index], [end index]);
• It can be used to make a current class method String x = “Hello ITC 316 students”
• It can be used to return the current class Instance String strSub = x.substring(0,3);
toUpperCase method
Example
void main() • Converts all characters in this string to upper case.
{ Example:
Student s1 = new Student('S001'); 'alphabet'.toUpperCase();
}
class Student replaceAll method
{ • Replaces all substrings that match from with replace.
var st_id; Example:
Student(var st_id) print(string.replaceAll('a', 'A'));
{ replaceFirst method
// using this keyword • Creates a new string with the first occurrence of from replaced by to.
this.st_id = st_id; Example:
print(“Student - Dart THIS Example"); print(string.replaceFirst('a', 'A'));
print("The Student ID is : ${st_id}"); replaceRange method
} • Replaces the substring from start to end with replacement.
} Example:
Static Keyword const string1 = 'Dart is fun';
• The static keyword is used for memory management of global data members. The static keyword final result = string1.replaceRange(8, null, 'open source');
can be applied to the fields and methods of a class. The static variables and methods are part of print(result);
the class instead of a specific instance.
• The static keyword is used for a class-level variable and method that is the same for every Trim(), TrimLeft(), TrimLeft() method
instance of a class, this means if a data member is static, it can be accessed without creating an • The string without any leading and trailing whitespace.
object. • If the string contains leading or trailing whitespace, a new string with no leading and no trailing
• The static keyword allows data members to persist Values between different instances of a class. whitespace is returned:
Example:
'\tDart is fun\n'.trim();

You might also like