DEV Community

Cover image for Hello World In Dart
Kinanee Samson
Kinanee Samson

Posted on • Updated on

Hello World In Dart

Dart, a statically typed programming language that was invented and released by Google in October 10, 2011. It was originally created to replace JavaScript in the browser, me and you know that the last part of the statement hasn't really happened yet. However this does not mean that Dart is a lame programming language with no use.

Dart found solace with flutter. The flutter framework for cross-platform mobile app development uses Dart as it's programming language. Flutter with Dart really abstracts away most of the complexity encountered when building cross-platform applications. With Flutter and Dart, you can write your code once and be sure it will be compiled to run on the web, mobile and even desktop.

Visit Netcreed to read more articles like this.

The goal of today's article is to get you to start using Dart as developer with experience using another programming language.

Installation

To install dart visit this address to install the recommended version for your operating system. This installation ships with the dart compiler and a dart2js compiler. The dart2js compiler transpiles dart code to JavaScript.

What is Dart?

Dart as a programming language is a compiled and statically typed, asynchronous programming language, it bears a similar syntax to some statically typed languages like TypeScript, if you are used to writing TypeScript code you will pick up Dart much faster because they look alike a lot. Dart code can be compiled to an executable binary that can be run on a PC if the need be or you can use the dart2js compiler that comes baked with Dart programming language to compile your Dart code to JavaScript, the dart2js compiler transpiles dart code to JavaScript code. Which most browsers can run.

By being a statically typed language this implies that the type of value a variable can store is specified before run time, once the variable has been annotated with that type, storing a different type of value inside that variable will lead to an error, since Dart has good support across most IDE/Text editors you will be hinted about the error before you compile your code.

Dart is also Object Oriented and also supports functional programming. Let's write some Dart code.

main(){
  print("hello world");
}

// hello world
Enter fullscreen mode Exit fullscreen mode

Every Dart code is expected to have a main function that serves as the entry point where the application will begin execution, although we could have other functions nested inside the main function or outside of it, however the main function is always required for every application we build with dart.

We use the print function to log out a message on the console. Commenting works very much like in other C family of languages, at the end of every line a semicolon is required to denote the end of a statement. Let's see how we can create variables.

Variables In Dart

There are reserved keyword for creating variable in dart just like in other programming language some of them you will have encountered if you have worked with JavaScript in the past. When a variable is declared in Dart, the type of the variable can be explicitly declared by annotating the variable with it's type or you can let Dart to automatically infer the type of value stored in the variable to it.

main(){
  var name = 'samson';
  print(name); // samson
  name = 24; // not possible
}
Enter fullscreen mode Exit fullscreen mode

The var keyword in dart is used to declare a variable and automatically infer the type of the value to the variable.

In the code block above, storing an integer inside the name variable will throw an error because dart has auto inferred the String type to the variable hence, it can only store strings.

main(){
  String name = 'John';
  int age = 25;
  double taxRate = 0.10;
  bool isAdult = true;
}
Enter fullscreen mode Exit fullscreen mode

By annotating the variable with a type it ensures that all future assignment of values to that variable will only be considered as legit if the type value matches the one specified when we created the variable. Above we saw some instances of using the var keyword to create variables in Dart, but it is not limited to the one above. Let's look at other variable declaration keyword.

main(){
  dynamic canHoldAnyType = 'sam';
  canHoldAnyType = true
  final age = 23 // Run time constant
  const birthYear = 1997 // Compile time constant
}
Enter fullscreen mode Exit fullscreen mode

The dynamic keyword let's us bypass type checking for a particular variable enabling us to store different types of values inside the variable. The final and const keyword are used to create constants, the const keyword allows one to create a constant that will evaluated at compile time, before our code is run, while the final keyword creates run time constant, i.e a constant that while our code is currently executing.

Lists

Dart has List for handling series of data in a collection, since Dart also supports generics like TypeScript so we can strongly type an array to expect only a specific type of values.

main (){
    List names = ['sam', 'frodo', 'pipin'];
    List<String> otherNames = ['TAA', 'AOC', 'AWB'];
    // otherNames cannot store integers
    otherNames.add(1) // Will throw an error in IDE
    otherNames.add('SKA') // Add an item to a list
    print(names[0]) // sam
    otherNames.remove('AWB') // Remove an item from a list
}
Enter fullscreen mode Exit fullscreen mode

Sets

Dart also supports sets, sets are like array but they ensure that each item inside them are unique. It is often useful when we want to create an array that stores unique items.

void main() {
  Set<String> names = { 'AWB', 'TAA', "AOC"};

  names.add('SKA'); // add an item
  print(names); // { AWB, TAA, AOC, SKA }
  names.remove('AWB'); // remove an item
  names.add('SKA'); // will be ignored

  String item = names.elementAt(2) // get an element at an index
  print(names); // { TAA, AOC, SKA }
}
Enter fullscreen mode Exit fullscreen mode

Control Flow

Conditionals

We handle conditional statements in Dart much like we do in other languages, however let's see a use case.

manin(){
  int age = 26

  if(age > 18){
    print('You are an adult')
  } else {
      print('Not for children')
  }
}
Enter fullscreen mode Exit fullscreen mode

You could also do switch statements as demonstrated below;

main(){
  String team = 'Liverpool';

  switch (team) {
    case 'Liverpool':
      print('Reds!');
      break;
    case 'Chelsea':
      print('Blues');
      break;
    default:
      print('Citizens');
  }
}
Enter fullscreen mode Exit fullscreen mode

Loops

Dart supports both for loop and while loop, as demonstrated below;

main(){
  List ids = [0, 3, 5, 6, 3, 6];

  var i = 0;
  for (i; i < ids.length; i++){
    print(ids[i]);
  }

  i = ids.length;
  while (i >  -1){
    print(ids[i]);
    i--;
  }
}
Enter fullscreen mode Exit fullscreen mode

Functions

Dart like any other programming language supports functional programming, and as such we can create higher order functions, e.g pass functions as arguments to other functions, return a function from another function and lot's more. The main function which we must have in all our dart application is a typical example of a function. The return type of a functions can also be strongly typed including the arguments that the function expects.

// function name
void main() {
  var adder = makeAdderFunc();
  print(adder(2, 3)); // functions accepting other functions as argument
}


int addNums(int numA, int numB){
  return numA + numB; 
}

makeAdderFunc(){
  return addNums; // returning a function from another function
}

Enter fullscreen mode Exit fullscreen mode

Dart supports anonymous functions and arrow functions just like in other languages.

void main(){
  List oddNums = [1, 3, 5, 7]
  // anonymous functions
  oddNums.forEach() oddNums.forEach((n){
    print(n);
  });
  // OR arrow functions
  print(oddNums.map((n) => n * 2));
}
Enter fullscreen mode Exit fullscreen mode

We can pass in optional arguments in dart using two methods, We can wrap the optional parameter inside square brackets or we can use named Parameters. Named parameters are similar to using object destructuring in JavaScript. If we use named parameters then each argument passed in should be named to match the parameters name.

void main() {
  print(makeAdder(2, 4)); // 6 
  print(makeAdder(4)); // 4

  // named parameters
  print(makeAdder2(a: 2, b: 3)); // 5
  print(makeAdder2(a: 4)); // 4
}

// square brackets
int makeAdder(int a, [int b=0]){ // using square brackets
  return a + b;
}

int makeAdder2({ a, int b: 0}){ // using named parameters
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

OOP in Dart

since Dart is an Oriented Language, we can work with classes to create complex objects from classes, dart supports encapsulation, polymorphism, abstraction and inheritance all out of the box.

void main() {
  Person sam = Person('Kalashin', 23);
  Admin superAdmin = Admin('super', 100000);
  sam.getProfile(); // { 'Name': 'Kalashin', 'Age': 23}
}

class Person {
  String _name;
  int age;

  Person(this._name, this.age);

  getProfile(){
      return { 'Name': this._name, 'Age': this.age }
  }

}

class Admin extends Person {
  Admin(String name, int age):super(name, age);
}
Enter fullscreen mode Exit fullscreen mode

The class keyword is used to create a new class, we all know that all every class requires a constructor to instantiate the class, in Dart the constructor bears the same name as the class, that's why the Person class has a method named after it likewise the Admin class has a method named after it. That is it's own constructor. However since it is inheriting from the Person class it calls super which is a reference to the parent class that it is inheriting from. In Dart there are no access modifiers but if we declare a property/variable with the underscore character _ it is private to it's class or library. There is no need to call the new keyword when instantiating a class, we can just invoke the class like a function. In dart everything we can store inside a variable is treated as an Object including functions too.

Getters And Setters

We can use getters and setters to get and set the value for a private property on a class. Getters don't require a parameter list so we omit the parenthesis right after the name of the getter.

void main() {
  Person sam = Person('Kalashin',23);
  print(sam.name); // Kalashin
  sam.name = 'Samson';
  print(sam.name); // Samson

}

class Person {
  String _name;
  int age;

  get name {
    return this._name;
  }

  set name(val){
    this._name = val;
  }

  Person(this._name, this.age);

}

Enter fullscreen mode Exit fullscreen mode

Dart looks a lot like JavaScript albeit with some few exceptions, this article was designed to beginner friendly for JavaScript developers, I do hope to cover more advanced topics in Dart as we go along. If you are familiar with Dart and I forgot to include something you think is relevant for beginners then feel free to share below, if you are looking for a more comprehensive approach then check this article, you can also checkout this video to get started. Thanks for reading hope you learnt something new.

Visit Netcreed to read more articles like this.

Latest comments (0)