In Dart, is there a difference in assigning values right away vs in constructor like in Java?
class Example {
int x = 3;
}
vs
class Example {
int x;
Example() {
x = 3;
}
}
I ask because when I was using Flutter and tried to assign a Function that uses setState to a variable, it was not possible with the former method but possible with the latter.
In your trivial case, it doesn't matter.
In general, you can initialize instance variables in a few ways:
Inline (field initializers)
class Example1 {
T x = value;
}
Advantages:
Direct, concise.
Member will be initialized in all constructors.
Can be used to initialize final or non-nullable members.
Member is initialized before invoking base class constructors, which is important when the base class constructor calls member functions that are overridden by the derived class.
Disadvantages:
Cannot depend on construction arguments.
Usually cannot depend on this since the initialization occurs before this becomes valid (i.e., cannot depend on other instance members). (An exception is if the member is initialized lazily by declaring it late. This requires the null-safety feature to be enabled.)
Initializer list
class Example2 {
T x;
Example2() : x = value;
}
Advantages:
Can be used to initialize final or non-nullable members.
Member is initialized before invoking base class constructors, which is important when the base class constructor calls member functions that are overridden by the derived class.
Can utilize construction arguments.
The initialized variable always refers to a member variable, never to a constructor parameter.
Disadvantages:
If the class has multiple constructors, initialization would need to be duplicated, or constructors should redirect to a common constructor.
Cannot depend on this since the initialization occurs before this becomes valid (i.e., cannot depend on other instance members).
Can initialize only members of the enclosing class. Because initializer lists are executed before invoking base class constructors, they cannot set base class members.
Constructor body
class Example3 {
T x;
Example3() {
x = value;
}
}
Advantages:
Can utilize construction arguments.
Can be used to perform more complicated initialization, such as cases where the member cannot be initialized via a single expression.
Can use this (i.e., can use other instance members).
Can be used to set base class members.
Disadvantages:
Cannot be used to initialize non-late final nor non-nullable members.
If the class has multiple constructors, initialization would need to be duplicated or initialization code would need to be refactored out (such as, but not limited to, redirecting to a common constructor).
Member is initialized after invoking base class constructors.
If the constructor has a parameter that shadows a member variable, it's easy to accidentally refer to the parameter instead of the member. (See https://github.com/dart-lang/linter/issues/2552 for details.)
There probably are some points I'm forgetting, but I think that should cover the main ones.
Direct, inline initialization occurs first, then initialization lists, then constructor bodies. Also see Difference between assigning the values in parameter list and initialiser list, which explains why this becomes valid only for the later stages of object initialization.
As an example where it matters where members are initialized:
class Base {
Base() {
doSomething();
}
void doSomething() {}
}
class DerivedEarly extends Base {
int? x;
DerivedEarly() : x = 42;
#override
void doSomething() => print(x);
}
class DerivedLate extends Base {
int? x;
DerivedLate() {
x = 42;
}
#override
void doSomething() => print(x);
}
void main() {
DerivedEarly(); // Prints: 42
DerivedLate(); // Prints: null
}
Related
I'm trying to call a static method from a generic type I receive.
Is that even possible?
Furthermore, I apply a Type constraint in order to only manipulate the object from its parent class.
Here is a short example of what I'm trying to achieve:
class A {
static func() {
print("A");
}
}
class B extends A {
static func() {
print("B");
}
}
concret<T extends A>() {
T.func(); // I expected a print('B')
}
main() {
concret<B>();
}
No, it's not possible.
Dart static method invocations are resolved at compile-time, so it's not possible to call them on type variables which only have a value at run-time.
If it was possible, it would be completely unsafe. Anyone can create a class C extending A which does not have a static func member and invoke concret<C>();. Since static members are not inherited, it would have to give you a run-time error, and there is nothing you can do to detect that at compile-time. That is the primary reason why it is not allowed.
In dart when creating a mixin, you can declare properties and methods like a class. When declaring a private property/method, it seems the inheriting class should also have access to this private member (see below for example).
Is there a way to access a mixin's private variable in the class using the mixin?
If it's not possible, how can I declare a member in the mixin object but make it private in the inheriting class's interface.
mixin.dart
mixin A {
String propertyOne = '1';
// This property is not accessible to any inheriting class.
int _privateProperty = 2;
}
class.dart
class B with A {
String get mixinString => propertyOne;
// This property is not accessible to the B class.
int get mixinInt => _privateProperty;
}
No. A property being library private means that you can only express its name inside the same library. In any other library, the identifier _privateProperty is a different name, one private to that other library.
If you cannot declare both mixin and class in the same library, and you definitely need access to the property, then you can do any number of things to allow that.
Make the property public and tell people not to use it except in subclasses. They still can if they want to.
Make the property public and mark it #protected, to have the analyzer tell people to not use it except in subclasses. They still can if they want to.
Keep the property private and provide a separate method to access it:
mixin A {
// This property is not accessible to any inheriting class.
int _privateProperty = 2;
static int getPrivateProperty(A a) => a._privateProperty;
static void setPrivateProperty(A a, int value) {
a._privateProperty = value;
}
}
Anyone can still get to the property if they really want to, but they need to know that
it comes from A.
I am new to Dart and Flutter. While I am going through tutorials, I got that we can make singleton using factory keyword. But after that, I got this code.
class AccountService {
static final _instance = AccountService._internal();
AccountService._internal();
static AccountService getInstance() {
return _instance;
}
}
My questions.
How does the code work?
when getInstance() get called?
is AccountService._internal() a constructor?
static final _instance = AccountService._internal(); - When this get called?
Please help me
Static fields in Dart are all lazy evaluated so they will first get its value the first time you access the field.
So:
When you call getInstance(), it will return the value of the field _instance. If this is the first time the field will be evaluated so AccountService._internal() is called. If it is second time, the value from previous access is reused.
First time you call the method somewhere in your code? If you are never calling the method, the object referenced by _instance will never be created.
Yes, it is a named constructor and because the name starts with "_" it is only available from the library this class is part of. By doing so, it is possible to restrict new objects from this class so only the class itself are allowed to create an instance.
It is called first time _instance is accessed. Since this name also starts with "_" it is only available from the library this class is part of.
The lazy initialization of static fields is described in the Dart specification with the following reasoning:
Static variable declarations with an initializing expression are initializedlazily (8.1).
The lazy semantics are given because we do not want a language where one tends to define expensive initialization computations, causing long application startup times. This is especially crucial for Dart, which must support the coding of client applications.
https://dart.dev/guides/language/specifications/DartLangSpec-v2.2.pdf
Added code example
class AccountService {
static final _instance = AccountService._internal();
AccountService._internal() {
print(':: Calling AccountService._internal constructor');
}
static AccountService getInstance() {
print(':: Calling getInstance()');
return _instance;
}
}
void main() {
print(':: Step 1');
AccountService.getInstance();
print(':: Step 2');
AccountService.getInstance();
print(':: End');
}
Output:
:: Start
:: Step 1
:: Calling getInstance()
:: Calling AccountService._internal constructor
:: Step 2
:: Calling getInstance()
:: End
I have a class like this:
class A extends B {
final Property<bool> property = Property<bool>(this);
}
class Property<T> {
Property(this.b);
final B b;
}
But I get an error on this saying:
Invalid reference to 'this' expression.
I believe I can't access this at that moment, probably because the object reference is not ready yet.
So I tried other forms of initializing that variable like:
class A extends B {
final Property<bool> property;
A() : property = Property<bool>(this);
}
But I get the same error.
The only thing that works is:
class A extends B {
Property<bool> property;
A() {
property = Property<bool>(this);
}
}
Which needs me to remove the final variable declaration, which is something I don't want to.
How can I initialize a final variable in Dart that needs a reference to the object itself?
You can't reference this in any initializers as this hasn't yet been initialized itself, so you won't be able to set Property<bool> property to be final.
If you're just trying to prevent modification of the value of property from outside the instance, you can use a private member and provide a getter to prevent modification. Given your example, that would look something like this:
class A extends B {
// Since there's no property setter, we've effectively disallowed
// outside modification of property.
Property<bool> get property => _property;
Property<bool> _property;
A() {
property = Property<bool>(this);
}
}
I have an abstract superclass with a factory that returns an instance of a subclass. Is it possible to have a method that is implemented only in superclass? In the following code, for instance, would it be possible to remove Wind::act()?
abstract class Element {
final String action; // what it does
String act() => action; // do it
factory Element() {
return new Wind();
}
}
class Wind implements Element {
final action = "blows";
act() => action; // Why is this necessary?
}
void main() {
print(new Element().act());
}
When removing Wind::act(), there is an error about it missing. Also, when extending rather than implementing the superclass, leaving out the subclass implementation doesn't cause an error. But with a factory method, extending is not an option.
To inherit functionality from Element in Wind, you need to either extend or mix-in Element in Wind. Merely implementing an interface will not inherit any implementation.
So, you need to have class Wind extends Element { ... }.
That's not currently possible because Element has no generative constructor that Wind can use as super-constructor. So, you need to add that too, and make sure to initialize the action field in that constructor.
class Element {
final String action;
Element._(this.action); // Generative constructor that Wind can use.
factory Element() = Wind; // Factory constructor creating a Wind.
String act() => action;
}
class Wind extends Element {
Wind() : super._("blows");
}
The generative constructor doesn't need to be private, but if you are declaring and using all the classes only inside your own library, it might as well be.
Another option is to have a separate ElementBase class containing the action field and act function and an empty-named generative constructor. Mixins are not a good choice in this case, because there is no good way to make action final when mixins can't have constructors.
abstract class Element {
String get action;
factory Element() = Wind;
String act();
}
class ElementBase implements Element {
final String action;
ElementBase(this.action);
String act() => action;
}
class Wind extends ElementBase {
Wind() : super("blow");
}
It's a common problem to want both a generative constructor for subclasses and a factory constructor generating the default implementation in an interface/skeleton class. The List and Map interfaces have this problem, and have solved it by exposing ListBase and MapBase. I think that is the best solution when you are exposing the superclass to other users in other libraries. If it's only used internally by yourself, I'll use the private/non-default-named generative constructor in the superclass.