I have the following class:
class EventableNumber{
num _val;
num get val => _val;
void set val(num v){
num oldValue = _val;
_val = v;
_controller.add(new NumberChangedEvent(oldValue, v));
}
StreamController<NumberChangedEvent> _controller = new StreamController<NumberChangedEvent>();
Stream<NumberChangedEvent> _stream;
Stream<NumberChangedEvent> get onChange => (_stream != null) ? _stream : _stream = _controller.stream.asBroadcastStream();
EventableNumber([num this._val = 0]);
}
Is it possible to overload the = assignment operator? rather than using the val getter and setter to enforce the event to fire when the value changes it would be nice if it could just be done when the user writes myEventableNum = 34 and then myEventableNum first its onChange event, rather than myEventableNum.val = 34.
Dart doesn't allow this.
However, have you considered a function style call?
Basically, if you define a function called 'call' in EventableNumber class, then you can call the instance as a function:
myEventableNum(34)
If you decided to go this way, it is recommended to implement the Function interface:
class EventableNumber implements Function {
...
void call(val) {...}
...
}
Hope this helps :)
Related
what ways you suggest for getting value from future in object constructor ?
class F{
late SomeObj<t> _obj;
F(){
() async{
_obj = await someFuture();
}.call();
}
somefunc() => doing something with _obj
}
but this doesn't gave me right res in the right time,
Other ways for this situation?
Here are two possible approaches:
Make your class's constructor private and force callers to instantiate your class via an asynchronous static method. From the perspective of callers, there is little difference between calling a static method and a named constructor.
class F {
late SomeObj<T> _obj;
F._();
static Future<F> create() async {
var f = F._();
f._obj = await someFuture();
return f;
}
Object? someFunc() => doSomethingWith(_obj);
}
Explicitly make everything that depends on the asynchronous value also asynchronous. If _obj is initialized asynchronously, then _obj should be a Future. If someFunc depends on _obj, then someFunc should return a Future.
class F {
Future<SomeObj<T>> _obj;
F() : _obj = someFuture();
Future<Object?> someFunc() async => doSomethingWith(await _obj);
}
This question already has an answer here:
Is there a difference in how member variables are initialized in Dart?
(1 answer)
Closed 1 year ago.
I'm trying to understand the following example where I try to initialize a final variable in a constructor.
1st example - works
void main() {
Test example = new Test(1,2);
print(example.a); //print gives 1
}
class Test
{
final int a;
int b;
Test(this.a, this.b);
}
2nd example doesn't work
void main() {
Test example = new Test(1,2);
print(example.a); //compiler throws an error
}
class Test
{
final int a;
int b;
Test(int a, int b){
this.a = a;
this.b = b;
}
}
and when i remove final then it works again
void main() {
Test example = new Test(1,2);
print(example.a); //print gives 1
}
class Test
{
int a;
int b;
Test(int a, int b){
this.a = a;
this.b = b;
}
}
what is the difference between the constructor in the 1st and the 2nd constructor why final initialization works with the first and doesn't with the 2nd.
Can anyone explain that to me please?
THanks
You cannot instantiate final fields in the constructor body.
Instance variables can be final, in which case they must be set exactly once. Initialize final, non-late instance variables at declaration, using a constructor parameter, or using a constructor’s initializer list:
Declare a constructor by creating a function with the same name as
its class (plus, optionally, an additional identifier as described in
Named constructors). The most common form of constructor, the
generative constructor, creates a new instance of a class
syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors):
My question refers to Methods inside of Classes via "public" access.
As referring to mql4 documentation, there seems to be no listed source on how to properly instantiate a Method into a Class, or what even makes a Method a Method in the first place.
To me it seems that if you place a function inside of a Class, that in itself makes it a Method? Or am I wrong. Is anyone able to clear this up for me?
Basic information and differences between constructor and method:
Constructor:
A constructor is a special function, which is called automatically when creating an object of a structure or class and is usually used to initialize class members,
The name of a constructor must match the class name,
The constructor has no return type (you can specify the void type).
(docs)
Method:
A method is a function that belongs to a class or an object, i.e. it cannot exist without the class.
You need to declare class methods in the class. Else it wouldn't be a class method.
Method can return value with type specified in the method declaration.
Simple example:
class MyClass { // Declaration
private:
string myName; // Property
public:
void printName(); // Method of void return type
int sumIntegers(int a, int b); // Method of int return type
MyClass(string name); // Constructor declaration
};
MyClass::MyClass(string name) { // Constructor body
this.myName = name;
}
int MyClass::sumIntegers(int a, int b) { //Method body
return a + b;
}
void MyClass::printName() {
Print("Your name is: ", this.myName);
}
int sumIntegers(int a, int b){ //Function body
return a + b;
}
Class member (object) initialization:
MyClass *myObject = new MyClass("SO example");
Example usage inside OnInit:
int OnInit() {
myObject.printName(); // Method call by object (MyClass)
Alert("2 + 2 = ", myObject.sumIntegers(2, 2)); // Same as above
Alert("2 + 2 = ", sumIntegers(2, 2)); // Function call
return(INIT_SUCCEEDED);
}
To me it seems that if you place a function inside of a Class, that in
itself makes it a Method?
Yes, but remember that a function is a block of code which only runs when it is called, and it's not related with a class.
Methods are related with class, and can not exists without a class.
I have these 2 methods in the same class, and I want to access a variable inside the second method. in C# we just set it to public variable.. but what about Dart and Flutter.. how to access this variable 'hours' in play method.
This is the way I tried but it tells me that it cannot recognize hours variable.
The problem is 'hours' variable is final and can not be declared at class level because it needs to be initialized and I want to initialize it only inside study method
class Student{
Future study(){
final hours = 5;
}
void play(){
int playhours = study().hours +2;
}
}
You cannot just make the variable global that you defined inside a function. What I normally do is that if I need to access a variable that will be set in another function of my class then I will define the variable outside the function and call it later when I need it. For your example I would do this:
class Student{
int hours;
Future study(){
hours = 5;
}
void play(){
//study(); You can call the function inside this one if you want
int playhours = hours + 2;
print(playhours.toString()); // Output: 7
}
}
Then when calling it:
void main() {
Student student = Student();
//student.study(); If you use it separately
student.play();
}
Another thing you could do is to return the value in your study() function!
Easy just do it like this:
class Student{
int hours;
Future study(){
hours = 5;
}
void play(){
//study(); You can call the function inside this one if you want
int playhours = hours + 2;
print(playhours.toString()); // Output: 7
}
}
then call it from the main function like this:
void main() {
Student().play();
}
I made a class and not sure why my getter is fine but the setter is showing as not defined in flutter.
class Test {
int range = 1000;
set setRng(int val) => range = val;
get getRng => range;
}
Test.getRng no errors..
Test.setRng(100) throws the error The method 'setRng' isn't defined for the class 'Test'
Clearly they're both defined..?
In Dart, you invoke setters with setter = value;. So your code can be modified like this:
test.setRng = 0;
Getters and setters make member functions look like member variables. By convention, they can then have variable like names, for example:
class Test {
int _range = 1000;
set range(int val) => _range = val; // optionally perform validation, etc
int get range => _range;
}
now it looks more natural when you use:
test.range = 123; // using the setter
print(test.range); // using the getter