This chapter is from the book

This chapter is from the book

One of the most attractive Dart enhancements is the ability to craft proper object taxonomies using object-oriented principles, such as inheritance and traditional design patterns. Dart offers many language features to help encapsulate code while making it easy to reuse behaviors, classes, and libraries. This chapter introduces you to the language features, and Chapter 5 looks at how to leverage these features by focusing on how Dart structures objects and their corresponding object scopes.

Variables

A variable is a named identifier accessible from within the current scope. Variables, depending on the object type, can store a reference to either a value or an object instance. Dart supports first-class functions, so variables can also store references to functions.

A variable statement in Dart consists of a type annotation, a unique named identifier, and an optional assignment. Dart supports the keyword var, which is shorthand to register the variable instance with an assigned type of dynamic.

In the following approach, you’re going to initialize a variable named company of type dynamic within the scope of the main() function.

main() {
var company = {'publisher': "Peachpit"};
}

The code runs, but by using var, any developer could come along and assign a string or a number to the variable. If you use Dart’s support for type annotations, you can ensure that any reference that is assigned to company is of type Map.

main() {
Map company = { 'publisher': "Peachpit"};
}

You cannot completely omit the type declaration or Dart will assume it’s an assignment to a previously declared variable, attempt to look up the name from within the current scope, and fail to find it.

Unlike similar languages, Dart does not support variable hoisting. Variable hoisting is the process of allowing variables that are declared later in the execution context of the same scope to resolve prior to actual declaration. In Dart, you must declare a variable prior to attempting to access it.