Flutter for Beginners
上QQ阅读APP看书,第一时间看更新

Hello world

The following code is a basic Dart script, so let's take a look:

main() { // the entrypoint of an Dart app
var a = 'world'; // declaring and initializing variable
print('hello $a'); // call function to print to display output
}

This code contains some basic language features that need highlighting:

  • Every Dart app must have an entry point top-level function (you can refer to Chapter 2Intermediate Dart Programming, for more information on top-level functions), that is, the main() function.
If you choose to run this code locally on your preconfigured machine with Dart SDK, save the contents to a Dart file, and then run it with a Dart tool in a Terminal, for example,  dart hello_world.dart. This will execute the main function of the Dart script.
  • As we have seen before, although Dart is type-safe, type annotations are optional. Here, we declare a variable with no type and assign a String literal to it.
  • A String literal can be surrounded with single or double quotes, for example, 'hello world' or "hello world".
  • To display output on the console, you can use the print() function (which is another top-level function).
  • With the string interpolation technique, the $a statement inside a String literal resolves the value of the a variable. Dart calls the object's toString() method.
We'll explore more about string interpolation later in this chapter, in the Dart types and variables section, when we talk about the string type.
  • We can use the //comment syntax to write single-line comments. Dart also has multiline comments with the /* comment */ syntax, as follows:
// this is a single line comment

/*
This is a long multiline comment
*/

Note the return type of the main function; as it was omitted in the example, it assumes the special dynamic type, which we will explore later.