Your First Flutter App: Polishing the App

Apr 12 2022 · Dart 2.14.1, Flutter 2.5, Visual Studio Code

Part 1: Introduction to Dart

09. Understand Variable Scope

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 08. Utilize Type Inference Next episode: 10. Conclusion

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 09. Understand Variable Scope

Variable scope is an important aspect when writing code. The scope of a variable depends on where in your program you define that variable. There are three possible scope levels in Dart:

  • First, there’s Global scope. These objects exist for the duration of the app and are accessible from anywhere.

  • Second, there’s Instance scope. This is for variables such as the _model property of GamePage variable. These objects are alive for as long as the object that owns them stays alive. In this case, the GamePage owns _model, so as long as the GamePage is around, so is _model.

  • Finally, there’s local scope. Objects with a local scope, such as the difference variable you created in _pointsForCurrentRound(), only exist for the duration of that method. As soon as the execution of the program leaves this method, the local objects are no longer accessible.

Let’s look at the top part of _pointsForCurrentRound().

Because the maximumScore and difference values are created inside the method, they have local scope. They only come into existence when the _pointsForCurrentRound() method is called and cease to exist when the method is done.

As soon as the pointsForCurrentRound() method completes - in other words, when there are no more statements for it to execute, the computer destroys the maximumScore and difference variables and their storage space is cleared out.

The _alertIsVisible and _model variables, however, live on forever… or at least for as long as the GamePage, who owns them does (which in this case, is until the user terminates the app). This type of variable is named a property, and its scope is the same as the scope of the object instance the property belongs to.