Publishers of technology books, eBooks, and videos for creative people

Home > Articles

Object Structures in Dart

  • Print
  • + Share This
This chapter from Write Web Apps with Dart: Develop and Design introduces you to the language features in Dart, including classes, class inheritance, polymorphism, interfaces, mixins, and more.
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.

main() {
  company = { 'publisher': "Peachpit"}; //throws method not found: 'company='
}
  • + Share This
  • 🔖 Save To Your Account