This section introduces Dart’s main features, from variables and operators to classes and libraries assuming you already know how to program in other languages, Learn more about the Dart core library, refer to the Dart Library Overview for more details about the language’s capabilities, refer to the Dart programming language specification for Dart support for single-line, multi-line, and document comments

  • Tip: Open the DartPadExperience most of Dart’s language features (To learn more)

Basic functions of Dart

The following code uses many of the basic Dart features:

// Define a function
printInteger(int aNumber) {
  print('The number is $aNumber. '); // Print to console.
}

// The application starts from here.
main() {
  var number = 42; // Declare and initialize a variable.
  printInteger(number); // Call the function.
}

Copy the code

Here is the code used for all (or nearly all) Dart applications: // Code comments Single-line comments. Dart also supports multi-line comments (/* annotated content */) and document comments for int data types. Some other built-in types include String, List, and bool 42 literals. A literal is a compiled constant. Print () is a handy way to print ‘… ‘ (or “…” String constant variableName string interpolation, (more advanced writing variableName string interpolation, (more advanced writing variableName string interpolation, (more advanced writing {expression}) : A string containing variables or expressions inside a string literal the main() program starts executing a function, which is a specific, required, top-level function. For more information, refer to The main() function var to define variables. Defining variables this way does not require specifying variable types ⚠️ Tip: Code is best to follow The conventions in The Dart Style Guide Dart Style Guide

Important concepts

When learning the Dart language, you should base your learning on the following facts and concepts

  • Everything you can put in a variable is an object, and every object is an instance of a class. Both numeric functions and NULL are objects. All objects inherit from the Object class
  • Although Dart is strongly typed, the type declaration is optional because Dart can infer types. In the above code, the number is inferred to be of type int. To specify that no type is required, use the special type Dynamic
  • Dart supports generic types such as List

    (List of integers) or List

    (List of objects of any type)

  • Dart supports top-level functions, such as main(), as well as functions bound to classes or objects (static and instance methods, respectively). You can also create functions within functions (nested or local)
  • Similarly, Dart supports top-level variables, as well as variables bound to classes or objects (static and instance variables). Instance variables are sometimes referred to as fields or attributes.
  • Unlike Java, Dart does not have a public protected private keyword. If an identifier begins with an underscore (_), the identifier is private to its library
  • An identifier begins with a letter or underscore (_) followed by any combination of letters and numbers.
  • The Dart syntax contains expressions(with a runtime value) and statements(with no runtime value) for example:
    • condition ? Expr1: The value of expr2 may be expr1 or expr2
    • Compare this to if-else statements, which have no value. A statement usually contains one or more expressions, whereas expressions cannot contain statements directly
  • The Dart tool prompts two types of problems: warning and error. A warning simply indicates that the code may not work properly, but it does not prevent the program from executing. The error can be a compile-time error or a run-time error. Compile-time errors prevent code execution; Runtime errors cause code to raise [exception] during execution (#exception)

annotation

Single-line comments

Single-line comments start with //. Anything between // and the end of the line change is ignored by the compiler.

void main() {
  // TODO: refactor into an AbstractLlamaGreetingFactory?
  print('Welcome to my Llama farm! ');
}
Copy the code

Multiline comment

Multi-line comments start with /* and end with /. Anything between/and */ is ignored by the compiler (documentation comments are not ignored). Multi-line comments can be nested

void main() {
  /* * This is a lot of work. Consider raising chickens. Llama larry = Llama(); larry.feed(); larry.exercise(); larry.clean(); * /
}
Copy the code

Documentation comments

A document comment can be a multi-line or single-line comment, starting with /// or /**. Using /// on consecutive lines has the same effect as multi-line document comments where the Dart compiler ignores all text unless enclosed in brackets. Use brackets to refer to classes, methods, fields, top-level variables, functions, and parameters. The symbols in parentheses are parsed in the lexical field of the documented program element. Here is a document comment referencing other classes and members:

/// A domesticated South American camelid (Lama glama).
///
/// Since Spanish times,
/// Andean cultures used camels as meat and transport animals.
class Llama {
  String name;

  /// Feed camels [Food].
  ///
  /// A typical llama eats a bale of hay every week.
  void feed(Food food) {
    // ...
  }

  /// Use [activity] to train camels
  /// [timeLimit] minutes.
  void exercise(Activity activity, int timeLimit) {
    // ...}}Copy the code

In the generated document, [Food] becomes a link to the API documentation for the Food class that parses the Dart code and generates the HTML document, available using the Documentation Generation Tool in the SDK. For examples of generated documentation, refer to Dart API Documentation. Please refer to the Guidelines for Dart Doc Comments for suggestions on document structure

The keyword

Dart language keyword list

abstract dynamic implements show
as else import static
assert enum in super
async export interface switch
await extends is sync
break external library this
case factory mixin throw
catch false new true
class final null try
const finally on typedef
continue for operator var
covariant Function part void
default get rethrow while
deferred hide return with
do if set yield

Avoid using these words as identifiers. However, keywords labeled with an upper label can be used as identifiers if necessary:

  • Words with a 1 superscript are context keywords that have meaning only in a particular place. They are valid identifiers everywhere
  • Words with 2 superscript are built-in identifiers. To simplify porting JavaScript code to Dart, these keywords are valid identifiers in most places, but they cannot be used as class or type names or as import prefixes
  • Words with 3 superscript are updates related to the asynchronous support added to Dart 1.0 as restricted class reserved words

You cannot use await or yield as identifiers in the body of any function labeled async, async* or sync*

  • The rest of the keyword list isReserved words. Reserved words cannot be used as identifiers