Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable outside any class: why is it possible

Tags:

flutter

dart

I have a file fancy_button.dart for a custom Flutter widget FancyButton which is like:

class FancyButton extends StatefulWidget {
    // ...
}

class _FancyButtonState extends State<FancyButton> {
    // ...
}

// Declaration outside any class:

Map<_FancyButtonState, Color> _buttonColors = {};

final _random = Random();

int next(int min, int max) => min + _random.nextInt(max - min);

// ...

The application works just fine. Notice that I declare and use some variables outside any class. Now my question is: how is it even possible? Shouldn't everything be inside a class in Dart, like Java?

like image 300
user3405291 Avatar asked Sep 08 '26 21:09

user3405291


2 Answers

No, Dart supports variables and functions defined in global space. You can see this with the main() method which are declared outside any class.

Also, global variables (and static class variables) are lazy evaluated so the value are first defined when you are trying to use them. So your runtime are not going to slow down even if there are a bunch of global variables there are not used.

like image 176
julemand101 Avatar answered Sep 11 '26 08:09

julemand101


Are you coming from Java before touching Dart?

Basically, Dart is not single-class-single-file like how Java works. Yes, it does support Object Oriented Programming (in kinda different way). The behavior of constructor is different. There is no public, private, and protected keywords. Please just refer to the official docs.

Anyway, you don't need a complex public static void main(). The real entry point is main(). Unless you define that function, you won't be able to run a file in command line.

like image 44
Haqqi Avatar answered Sep 11 '26 07:09

Haqqi