Introduction to Dart for JavaScript Developers

Domains: Flutter

Like React Native, Flutter uses reactive-style views. However, while RN transpiles to native widgets, Flutter compiles all the way to native code. Flutter controls each pixel on the screen, which avoids performance problems caused by the need for a JavaScript bridge.

Dart is an easy language to learn and offers the following features:

  • Provides an open-source, scalable programming language for building web, server, and mobile apps.
  • Provides an object-oriented, single inheritance language that uses a C-style syntax that is AOT-compiled into native.
  • Transcompiles optionally into JavaScript.
  • Supports interfaces and abstract classes.

A few examples of the differences between JavaScript and Dart are described below.

Entry point

JavaScript doesn’t have a pre-defined entry function - you define the entry point.

// JavaScript
function startHere() {
  // Can be used as entry point
}

In Dart, every app must have a top-level main() function that serves as the entry point to the app.

// Dart
main() {
}

Try it out in DartPad.

Printing to the console

To print to the console in Dart, use print().

// JavaScript
console.log('Hello world!');
// Dart
print('Hello world!');

Try it out in DartPad.

Variables

Dart is type safe—it uses a combination of static type checking and runtime checks to ensure that a variable’s value always matches the variable’s static type. Although types are mandatory, some type annotations are optional because Dart performs type inference.

Creating and assigning variables

In JavaScript, variables cannot be typed.

In Dart, variables must either be explicitly typed or the type system must infer the proper type automatically.

// JavaScript
var name = 'JavaScript';
// Dart
String name = 'dart'; // Explicitly typed as a string.
var otherName = 'Dart'; // Inferred string.
// Both are acceptable in Dart.

Try it out in DartPad.

For more information, see Dart’s Type System.

Default value

In JavaScript, uninitialized variables are undefined.

In Dart, uninitialized variables have an initial value of null. Because numbers are objects in Dart, even uninitialized variables with numeric types have the value null.

// JavaScript
var name; // == undefined
// Dart
var name; // == null
int x; // == null

Try it out in DartPad.

For more information, see the documentation on variables.

Checking for null or zero

In JavaScript, values of 1 or any non-null objects are treated as true.

// JavaScript
var myNull = null;
if (!myNull) {
  console.log('null is treated as false');
}
var zero = 0;
if (!zero) {
  console.log('0 is treated as false');
}

In Dart, only the boolean value true is treated as true.

// Dart
var myNull = null;
if (myNull == null) {
  print('use "== null" to check null');
}
var zero = 0;
if (zero == 0) {
  print('use "== 0" to check zero');
}

Try it out in DartPad.

Functions

Dart and JavaScript functions are generally similar. The primary difference is the declaration.

// JavaScript
function fn() {
  return true;
}
// Dart
fn() {
  return true;
}
// can also be written as
bool fn() {
  return true;
}

Try it out in DartPad.

For more information, see the documentation on functions.

Asynchronous programming

Futures

Like JavaScript, Dart supports single-threaded execution. In JavaScript, the Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Dart uses Future objects to handle this.

// JavaScript
class Example {
  _getIPAddress() {
    const url = 'https://httpbin.org/ip';
    return fetch(url)
      .then(response => response.json())
      .then(responseJson => {
        const ip = responseJson.origin;
        return ip;
      });
  }
}

function main() {
  const example = new Example();
  example
    ._getIPAddress()
    .then(ip => console.log(ip))
    .catch(error => console.error(error));
}

main();
// Dart
import 'dart:convert';
import 'package:http/http.dart' as http;

class Example {
  Future<String> _getIPAddress() {
    final url = 'https://httpbin.org/ip';
    return http.get(url).then((response) {
      String ip = jsonDecode(response.body)['origin'];
      return ip;
    });
  }
}

main() {
  final example = new Example();
  example
      ._getIPAddress()
      .then((ip) => print(ip))
      .catchError((error) => print(error));
}

For more information, see the documentation on Futures.

async and await

The async function declaration defines an asynchronous function.

In JavaScript, the async function returns a Promise. The await operator is used to wait for a Promise.

// JavaScript
class Example {
  async function _getIPAddress() {
    const url = 'https://httpbin.org/ip';
    const response = await fetch(url);
    const json = await response.json();
    const data = await json.origin;
    return data;
  }
}

async function main() {
  const example = new Example();
  try {
    const ip = await example._getIPAddress();
    console.log(ip);
  } catch (error) {
    console.error(error);
  }
}

main();

In Dart, an async function returns a Future, and the body of the function is scheduled for execution later. The await operator is used to wait for a Future.

// Dart
import 'dart:convert';
import 'package:http/http.dart' as http;

class Example {
  Future<String> _getIPAddress() async {
    final url = 'https://httpbin.org/ip';
    final response = await http.get(url);
    String ip = jsonDecode(response.body)['origin'];
    return ip;
  }
}

main() async {
  final example = new Example();
  try {
    final ip = await example._getIPAddress();
    print(ip);
  } catch (error) {
    print(error);
  }
}

For more information, see the documentation for async and await.

Similar pages

Page structure
Terms

Flutter