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

Top-level functions and variables

In this chapter, we have seen that functions and variables in Dart can be tied to classes as members—class fields and methods.

The top-level way of writing functions is also already known from Chapter 1An Introduction to Dart, where we wrote the most famous Dart function: the entry point of every application, main(). For variables, the way of declaring is the same. We just leave it out of any function scope, so that it's accessible globally on the application/package:

var globalNumber = 100;
final globalFinalNumber = 1000;

void printHello() {
print("""Dart from global scope.
This is a top-level number: $globalNumber
This is a top-level final number: $globalFinalNumber
""");
}

main() {
// the most famous Dart top level function
printHello(); // prints the default value

globalNumber = 0;
// globalFinalNumber = 0; // does not compile as this is a final variable

printHello(); // prints the new value
}

As you can see, variables and functions do not need to be bound to a class to exist. This is the flexibility proposed by the Dart language, bringing to the developer the ability to write simple and consistent code, without forgetting the patterns and features of modern languages.