Dart Programming - Syntax


Advertisements

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

Your First Dart Code

Let us start with the traditional “Hello World” example −

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. print() is a predefined function that prints the specified string or value to the standard output i.e. the terminal.

The output of the above code will be −

Hello World!

Execute a Dart Program

You can execute a Dart program in two ways −

  • Via the terminal
  • Via the WebStorm IDE

Via the Terminal

To execute a Dart program via the terminal −

  • Navigate to the path of the current project
  • Type the following command in the Terminal window
dart file_name.dart

Via the WebStorm IDE

To execute a Dart program via the WebStorm IDE −

  • Right-click the Dart script file on the IDE. (The file should contain the main() function to enable execution)

  • Click on the ‘Run <file_name>’ option. A screenshot of the same is given below −

Run Test1 Dart

One can alternatively click the Run Button button or use the shortcut Ctrl+Shift+F10 to execute the Dart Script.

Dart Command-Line Options

Dart command-line options are used to modify Dart Script execution. Common commandline options for Dart include the following −

Sr.No Command-Line Option & Description
1 -c or --c

Enables both assertions and type checks (checked mode).

2 --version

Displays VM version information.

3 --packages <path>

Specifies the path to the package resolution configuration file.

4 -p <path>

Specifies where to find imported libraries. This option cannot be used with --packages.

5 -h or --help

Displays help.

Enabling Checked Mode

Dart programs run in two modes namely −

  • Checked Mode
  • Production Mode (Default)

It is recommended to run the Dart VM in checked mode during development and testing, since it adds warnings and errors to aid development and debugging process. The checked mode enforces various checks like type-checking etc. To turn on the checked mode, add the -c or –-checked option before the script-file name while running the script.

However, to ensure performance benefit while running the script, it is recommended to run the script in the production mode.

Consider the following Test.dart script file −

void main() { 
   int n = "hello"; 
   print(n); 
} 

Run the script by entering −

dart Test.dart

Though there is a type-mismatch the script executes successfully as the checked mode is turned off. The script will result in the following output −

hello

Now try executing the script with the "- - checked" or the "-c" option −

dart -c Test.dart 

Or,

dart - - checked Test.dart

The Dart VM will throw an error stating that there is a type mismatch.

Unhandled exception: 
type 'String' is not a subtype of type 'int' of 'n' where 
   String is from dart:core 
   int is from dart:core 
#0  main (file:///C:/Users/Administrator/Desktop/test.dart:3:9) 
#1  _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart :261) 
#2  _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)

Identifiers in Dart

Identifiers are names given to elements in a program like variables, functions etc. The rules for identifiers are −

Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit.

  • Identifiers cannot include special symbols except for underscore (_) or a 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
first_name first name
num1 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

Whitespace 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

// this is single line comment  
  
/* This is a   
   Multi-line comment  
*/ 

Object-Oriented Programming in Dart

Dart is an Object-Oriented language. Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods.

  • Object − An object is a real-time representation of any entity. As per Grady Brooch, every object must have three features −

    • State − described by the attributes of an object.

    • Behavior − describes how the object will act.

    • Identity − a unique value that distinguishes an object from a set of similar such objects.

  • Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object.

  • Method − Methods facilitate communication between objects.

Example: Dart and Object Orientation

class TestClass {   
   void disp() {     
      print("Hello World"); 
   } 
}  
void main() {   
   TestClass c = new TestClass();   
   c.disp();  
}

The above example defines a class TestClass. The class has a method disp(). The method prints the string “Hello World” on the terminal. The new keyword creates an object of the class. The object invokes the method disp().

The code should produce the following output

Hello World
Advertisements