Share
Flutter Mobile App. Development

Course Outline

Week 1

Introduction To Dart Programming Language

  • Overview
  • Environment
  • Variables
  • Operators
Week 2
Week 3
Week 4
Week 5
Week 6
Week 7
Week 8
Week 9
Week 10
Week 11
Week 12
Week 13

SponsoredAdvertise

INTRODUCTION TO DART PROGRAMMING

INTRODUCTION TO DART PROGRAMMING LANGUAGE

 

Dart is an open-source general-purpose programming language. It is originally developed by Google. Flutter is based on the Dart programming language and so is necessary we get familiarized with the Dart programming language before starting flutter.

 

Dart is a new programming language meant for the server as well as the browser.Introduced by Google, the Dart SDK ships with its compiler – the Dart VM. The SDK also includes a utility -dart2js,a transpiler that generates JavaScript equivalent of a Dart Script.

 

A source-to-source translator, source-to-source compiler (S2S compiler), transcompiler,or transpiler is a type of translator that takes the source code of a program written in a programming language as its input and produces an equivalent source code in the same or a different programming language. A source-to-source translator converts between programming languages that operate at approximately the same level of abstraction, while a traditional compiler translates from a higher level programming language to a lower level programming language. For example, a source-to-source compiler may perform a translation of a program from Python to JavaScript, while a traditional compiler translates from a language like C to assembler or Java to byte code.


Dart Programming –Overview


Dart is an object-oriented language which can trans compile into JavaScript. It supports a varied range of programming aids like interfaces, classes,collections, generics, and optional typing.

Dart can be extensively used to create single-page applications. Single-page applications apply only to websites and web applications. Single-page applications enable navigation between different screens of the website without loading a different web page in the browser. A classic example is GMail. When you click on a message in your inbox, browser stays on the same web page,but JavaScript code hides the inbox and brings the message body on screen.

 

Executing Script Online with DartPad

 

You may test your scripts online by using the online editor at https://dartpad.dartlang.org/. The Dart Editor executes the script and displays both HTML as well as console output. The online editor is shipped with a set of preset code samples.

 

Dartpad

 

Figure: DartPad


You can visit the online editor and try the code below:

void main() {

   print('hello world');

}

 

 

Figure: Sample code in the Online DartPad

 

Setting Up the Local Environment

 

Using the Text Editor

 

Examples of a few editors include Windows Notepad, Notepad++, Emacs, vim or vi, etc.Editors may vary from one Operating System to another. The source files are typically named with the extension ".dart".

 

Installing the Dart SDK

 

The current stable version of Dart is 1.21.0. 


The dart sdk can be downloaded from

 

http://www.gekorm.com/dart-windows/

 

Dart Installation


Figure: Dart Setup Wizard

 

 

Figure: Dart Installation

 

During the installation, you could see the path to the dart bin

From the above figure, the dart sdk path will be

C:\ProgramFiles\Dart\dark-sdk\bin


 

Figure: Installation Complete


On completion of the SDK installation, set the PATH environment variable to –

<dart-sdk-path>\bin

To set up the Path variable, search env in the search bar


 

Click on Edit the system environment variables

 


Figure: EnvironmentVariables


Click on the Environment Variables

  

 

Figure: Environment Variable

The above Environment Variables has Path already so I only need to double click on the Path to add a new entry which is the path of the dart sdk. For windows 8,you will have to add ; to the previous variable before adding your dart path to it.

 

You can open your C:\Program Files to check the path of your dark sdk.

 Mine looks like this:


 

Figure: Path to dart sdk.

Hence the path to my dart sdk will be:

C:\Program Files\Dart\dart-sdk\bin

You can just double click on the top path and copy the path and add \bin to it

If your Environment Variables doesn’t have Path in it, click on New and Enter the Variable Name Path and value path to your dart sdk/bin

 

 

Figure: Entering new variable name for Path

When done, you can click on Ok 


Verifying the Installation


To verify if Dart has been successfully installed, open the command prompt and enter the following command:

 

Dart

To open the command prompt, search cmd in the search bar and press enter

 


Figure: Searching for the command prompt


 

Figure: Command prompt

 

Once the command prompt shows up, type Dart and press the enter key

 

If installation is successful, it will show the dart runtime.

 

 

Figure: Dart in the command prompt

 

 

Figure: Successful dart installation

 

INTEGRATED DEVELOPMENT ENVIRONMENT (IDE) SUPPORT

 

Many IDEs support scripting in Dart. Examples include Eclipse, IntelliJ, and WebStorm from Jet brains.

InelliJ and WebStorm are paid editors after the 30-day trials. Eclipse is free and fully supported by donation. In this course we will be using the Eclipse IDE. You can also use the online DartPad if you wish or either Notepad or Notepad++


INSTALLATION OF ECLIPSE IDE

Before you install Eclipse, make sure you've downloaded and installed Dart as explained above.

1. Get the latest version of eclipse from:


https://www.eclipse.org/downloads/


2. Install the downloaded file


3. Choose the type of development you wish to use Eclipse for.


You can choose PHP since we will be using PHP at a point of our Flutter Mobile Application Development.

You can add more plugins later when you visit the Eclipse marketplace for extensions when the need be. For instance if you are taking the Java Programming course, you will need to extend your Eclipse for Java Development.


4. Visit the market place and search Dart. Install the Dart plugin that appears.


NOTE


You need to install Java Runtime Environment before you start the installation of Eclipse. Without it, you will get this page alert for you to install Java Runtime Environment


Image


Figure: Java Runtime Environment Installation Alert


So you can click on the latest Oracle JDK and install and start your eclipse installation again.


In the video I didn't encounter this error before I have previously installed the Java Runtime Environment.


CREATING YOUR DART PROGRAM IN ECLIPSE


1. Click on File → New  Project


Image


Figure: Creating your Dart Project


2. Click on Dart → Dart Project


Image


Figure: Selecting Dart Project option


3. Fill the form


Image


Figure: Fill the form


To easily locate your source codes for reference, I will entreat you to save your project base on the week number so you'll know where to go when you want to make reference to a source code taught in a particular week.


You can create a folder to save your dart projects. If you have a project folder, unchecked the Use default location and click on the Browse to navigate to that folder to change the default folder Eclipse recommended.


4. Click on Finish


ADDING A DART FILE TO PROJECT


1. Right click on the project name and select


New → File


Image


Figure: Adding a new dart file


2. Give the file a name with the .dart extension. My example is hello.dart


Image


3. Click on Finish


RUNNING YOUR DART FILE


1. Click on the dart file


2. Click on the run icon Image


3. To run the entire Dart Project, click on Run as Dart Program and to run the select dart file, click on Run File


Image


Figure: Running a Dart Program or File


NOTE: If you select the Run as Dart Program, it will try to locate main.dart file because dart runs it program from the main.dart file. If your project doesn't have a main.dart in it, you will get an error as shown below:


Error when reading 'C:\Users\GodwinTawiah\eclipse-workspace\Dart_Programming_Week_1\main.dart': No such file or directory.

Could not find a command named "C:\Users\GodwinTawiah\eclipse-workspace\Dart_Programming_Week_1\main.dart".

Usage: dart [] []

Global options:

-h, --help                              Print this usage information.

-v, --verbose                           Show additional command output.

    --version                           Print the Dart SDK version.

    --enable-analytics                  Enable anonymous analytics.

    --disable-analytics                 Disable anonymous analytics.

    --enable-experiment=    Enable one or more experimental features.

                                        [extension-methods, non-nullable, nonfunction-type-aliases, triple-shift, variance]

Available commands:

  analyze   Analyze the project's Dart code.

  compile   Compile Dart to various formats.

  create    Create a new project.

  format    Idiomatically formats Dart source code.

  migrate   Perform a null safety migration on a project or package.

  pub       Work with packages.

  run       Run a Dart file.

  test      Runs tests in this project.

Run "dart help " for more information about a command.


Figure: Error running Dart as Program


Alternatively, you can right click on the project or dart file and select run. Then choose your appropriate option. 

When the project as main.dart file and you want to run the entire project, choose Run as Dart Program but when running a dart file which is not main.dart, choose Run as file option.


You can copy and paste this code in your dart file and run:


void main() {

   print('hello world');

}


This should output hello world


You can change the hello world  text to some phrase or sentence and run again. You'll realize whatever text you put in the double quotation in the print() is displayed on the console screen


Image


Figure: Dart Program displaying the name of a person


Syntax

Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. 

A Dart program is composed of:

  • Variables and Operators
  • Classes
  • Functions
  • Expressions and Programming Constructs
  • Decision Making and Looping Constructs
  • Comments
  • Libraries and Packages
  • Typedefs
  • Data structures represented as Collections / Generics

 

Explanation To Your First Dart Code

main(){

   print("Hello World!");

}

 

The main() function is a predefined method in Dart. This method acts as the entry point to the application. A Dart script needs the main() method for execution.

The print() is a predefined function that prints the specified string or value to the standard output i.e. the terminal.

 

Execute a Dart Program

 

You can execute a Dart program in two ways. Either in a terminal or using an IDE

 

In this course, we will either write our dart code in either Notepad or Notepad++ and run on the terminal or use the Eclipse IDE we installed.

 

Those who wish to use the terminal to execute their Dart Program can download Notepad++ or use the Notepad available on all windows operating systems. 


You can download Notepad++ at:


https://notepad-plus-plus.org/downloads/


Executing in a terminal

 

1.Create a folder you will be saving your dart project inside

2.Open a notepad or notepad ++ and copy and paste the above dart code and save the file as hello.dart

3.Open a command prompt

4.Navigate to where your project is saved. To move out of a directory, use the command cd.. and to move to a directory, use the command cd

For example, when the image below is my command prompt when started

 

 

Figure: command prompt when started

 

My dart file is in a folder by name dart_projects in the c directory. Iwill therefore have to move out of two directories (GodwinTawiah and Users) andso I will use the cd.. command twice.

 

Thus:

 

Figure: Moving to the c directory

 

NowI can move to my dart_projects folder using the cd command

 

 

Figure: In dart project folder

 

Now that I am in the dart_projects folder which contain my dart file hello.dart, I can run the command dart hello.dart

 


Figure:Dart program successfully run

 

Identifiers in Dart

Identifiers are names given to elements in a program like variables, functions etc. 

Rules for identifiers

  • Identifiers can include both, characters and digits. However, the identifier cannot begin witha digit.
  • Identifiers cannot include special symbols except for underscore (_) ora dollar sign ($).
  • Identifiers cannot be keywords.
  • They must be unique.
  • Identifiers are case-sensitive.
  • Identifiers cannot contain spaces.


The following tables lists a few examples of valid and invalid identifiers

 

Valid identifiers Invalid identifiers
firstName Var
lastName first name
num_1 first-name
$result 1number

 

Keywords in Dart

Keywords have a special meaning in the context of a language. The following table lists some keywords in Dart.

abstract 1 continue false new this
as 1 default final null throw
assert deferred 1 finally operator 1 true
async 2 do for part 1 try
async* 2 dynamic 1 get 1 rethrow typedef 1
await 2 else if return var
break enum implements 1 set 1 void
case export 1 import 1 static 1 while
catch external 1 in super with
class extends is switch yield 2
const factory 1 library 1 sync* 2 yield* 2

 

White space and Line Breaks

 

Dart ignores spaces, tabs, and newlines that appear in programs. You can use spaces,tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.

 

Dart is Case-sensitive

 

Dart is case-sensitive. This means that Dart differentiates between uppercase and lowercase characters.

 

Statements end with a Semicolon

Each line of instruction is called a statement. Each dart statement must end with a semicolon (;). A single line can contain multiple statements. However, these statements must be separated by a semicolon.

 

Comments in Dart

 

Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct etc. Comments are ignored by the compiler.

 

Dart supports the following types of comments:

 

Single-line comments ( // ) − Any text between a "//" and the end of a line is treated as a comment

 

Multi-line comments (/* */) − These comments may span multiple lines.

 

Example

 

//I am a comment.

/*I am a block comment

    I can write as many lines within this these stars

*/


Dart Programming -Data Types

 

One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.

 

The Dart language supports the following types:

 

  • Numbers
  • Strings
  • Booleans
  • Lists
  • Maps
  • Numbers

 

Numbers in Dart are used to represent numeric literals. The Numbers in Dart are declared as:

 

Integer − Integer values represent non-fractional values, i.e., numeric values without a decimal point.For example, the value "10" is an integer. Integer literals are represented using the int keyword.

 

Double − Dart also supports fractional numeric values i.e. values with decimal points.

 

Strings

 

Strings represent a sequence of characters. For instance, if you were to store some data like name, address, phone, town, city etc. the string data type should be used.

 

The keyword String is used to represent string literals. String values are embedded in either single or double quotes.

 

Boolean

 

The Boolean data type represents Boolean values true and false. Dart uses the bool keyword to represent a Boolean value.

 

List and Map

 

The data types list and map are used to represent a collection of objects. A List is an ordered group of objects.

 

The List data type in Dart is synonymous to the concept of an array in other programming languages.

The Map data type represents a set of values as key-value pairs. The dart: core library enables creation and manipulation of these collections through the predefined List and Map classes respectively.


The Dynamic Type

Dart is an optionally typed language. If the type of a variable is not explicitly specified, the variable’s type is dynamic. The dynamic keyword can also be used as a type annotation explicitly.


Variables

A variable is “a named space in the memory” that stores values. In other words,it acts a container for values in a program. Variable names are called identifiers.

 

 

Rules for naming variables

  • Identifiers cannot be keywords.
  •  
  • Identifiers can contain alphabets and numbers.
  •  
  • Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.
  •  
  • Variable names cannot begin with a number.

 

Syntax

 

A variable must be declared before it is used. Dart uses the var keyword to achieve the same.

 

Data type (Either int, double, String, bool etc) nameOfVariable

 

Example to declare a variable to store the name of a person, we could declare as below:

 

String name;

String firstName;

String lastName;

 

To declare a variable to store the ages of students in a class, we could declare as below:

 

int age;

 

To declare a variable to store the salary of workers, we could declare as below:

 

double salary;

 

To declare a variable to store whether a person is under age or not, we could declare as below:

 

bool is_underage;

You could use the keyword var to declare a variable without specifying the datatype but you will have to assign a value to that variable.

 

Assigning a value to a variable sampling means storing value in the variable and this is done programmable using the = key.

 

Examples:

 

Var firstName = “Godwin”;

Var lastName = “Ashong”;

Va rage = 20;

You will get syntax error when you assign wrong values to a declared variable of different data type.

For example:

String firstName;

firstName= 1;

In this example 1 is an integer value but I am assigning it to a String variableso there will be a syntax error.

All uninitialized variables have an initial value of null. This is because Dart considers all values as objects. Uninitialized variables are variables which has not be assigned a value yet.

 

Consider this code. Copy and paste it in a dart file and run the file.

 

void main() {

   int num;

   print(num);

}


Output

Null

 

Final and Const

 

The final and const keyword are used to declare constants. Dart prevents modifying the values of a variable declared using the final or const keyword. These keywords can be used in conjunction with the variable’s data type or instead ofthe var keyword.

 

The const keyword is used to represent a compile-time constant. Variables declared using the const keyword are implicitly final.


Syntax: final Keyword


final variableName = value;

or

final dataType  variableName = value;


Syntax: const Keyword


const variableName = value;

or

const dataType variableName = value;

 

Examples


Final Example


void main() {

   final age = 18;

   print(age);

}


const Keyword


void main() {

   const pi = 3.142;

   double radius = 5;

   double area = pi*radius*radius;

   print("The output is ${area}");

}


NOTE: Once a variable is declared as a constant a value must be assigned at the time of declaration and the value should never be changed (No new value should be assigned).Otherwise there will be syntax error.


You can modify the value of the  pi as in the code below and run and see the output


void main() {

   const pi = 3.142;

   double radius = 5;

   double area = pi*radius*radius;

   pi = 3.14;

   print("The output is ${area}");

}


When you run you will get a syntax error that you can’t assign to the constant variable pi


Arithmetic Operators

 

Operators Meaning
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulus / Remainder
++ Increment
-- Decrement

 

EXAMPLES


void main() {

   double a = 5;

   double b = 2;

   double c = a+b;

   double d = a/b;

   double e = a*b;

   double f = a%b;

  

   print("${a} + ${b} = ${c} ");

   print("${a} / ${b} = ${d} ");

   print("${a} x ${b} = ${e} ");

   print("${a} mod ${b} = ${f} ");

   double g = a;

   a++; //Increase the value of a

   double h = a; //Assign the new value to h

   print("${g} increment = ${h} "); //Display result

   a--; //Decrease the value of a

   double i= a; //Assign the new value to i

   print("${h} decrement = ${i} "); //Print the result

}


 

 

Figure: Output

SponsoredAdvertise

Kuulchat Premium