Reputation: 7961
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?
Upvotes: 6
Views: 3966
Reputation: 1079
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.
Upvotes: 2
Reputation: 31259
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.
Upvotes: 9