Dart The method 'setRng' isn't defined for the class - flutter

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

Related

(Mql4) What differentiates a "Method" from a "Constructor"?

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.

How to return multiple types of class types from single generic class in dart flutter?

I have multiple class like this:-
Class A {
static int xyz = 10;
int c;
int d;
static A getData() {
// Do something
return A()..c = xyz*5;
}
Class B {
static int abc = 10;
int c;
static B getData() {
// Do something
return B()..c = xyz*5;
}
So, here you can see that the the getData() is doing the same thing, but have different return types.
Is there any way to avoid duplicate implementation like this, can it be done by defining a single function which can reference the class and have multiple return type?
This has two parts: creating the object, and assigning to a field of the object.
Creating the object, you are mostly out of luck. The only way to create an object of a specific type in a generic method is by using reflection via dart:mirrors. However, you have indicated that this is for a Flutter project, and Flutter doesn't support reflection, so that isn't an option. The only way you are going to be able to dynamically create an object is to pass in a factory method that the generic method can call to construct the object.
Assigning to a field of the object is easier, but it requires that you either lose static type checking by using dynamic or by tying your classes together with inheritance. The latter is the preferable choice, but if you are working with a library than it isn't always an option.
Combining these two things, the code will look like this:
class Foo {
static int xyz = 10;
int c;
}
class A extends Foo {
int d;
static A getData() {
return modifyObject(() => A());
}
}
class B extends Foo {
static B getData() {
return modifyObject(() => B());
}
}
T modifyObject<T extends Foo>(T create()) {
return create()..c = Foo.xyz * 5;
}
Before doing this, though, I'd take a look at whether your project actually needs it. If your use case is as simple as your example, I would argue that this level of generalization is overkill and you are hurting your code's readability more than you are helping its modularity.

Dart Named constructor vs Static method what to prefer?

So after dart made new keyword optional,
we can initialize an object with exact same syntax but different internal implementation.
class Color {
int r = 0, g = 0, b = 0;
Color({this.r, this.b, this.g});
//Named constructors
Color.red() //Implementation
Color.cyan() //Implementation
// Static Initializers
static Color red() => //Initialze with parameter
static Color cyan() => //Initialze with parameter
}
We can use them like this regardless of being it a named constructor or static method:
Color red = Color.red();
Color cyan = Color.cyan();
What is the place to use each of them?
In practice there is little difference between a factory constructor and a static method.
For a generic class, it changes where you can (and must) write a type parameter:
class Box<T> {
T value;
Box._(this.value);
factory Box.withValue(this.value) => Box<T>._(value);
static Box<T> fromValue<T>(T value) => Box<T>._(value);
}
...
var box1 = Box<int>.withValue(1);
var box2 = Box.fromValue<int>(2);
So, for generic classes, factory constructors are often what you want. They have the most pleasant syntax.
For non-generic classes, there is very little difference, so it's mainly about signaling intent. And deciding which category the name goes into in the DartDoc.
If the main objective of the function is to create a new object, make it a constructor.
If the main objective is to do some computation and eventually return an object (even if it's a new object), make it a static function.
That's why parse methods are generally static functions.
In short, do what feels right for your API.
Constructors and static functions are different. You usually create a named constructor that returns an instance of an object with some predefined values. For example, you have a class called Person which stores Name and Job. You can create this named constructor Person.doctor(name) which you will return a Person object with Job = 'doctor'
class Person{
final name;
final job;
Person(this.name, this.job);
Person.doctor(this.name, {this.job = "doctor"});
}
Static functions or variable persists on all the instance of a class. Let us say, Person has a static variable called count. You increment the count variable whenever an instance of Person is created. You can call Person.count anywhere later in your code to get the value of count (Number of instances of Person)
class Person{
final name;
final job;
static int count;
Person(this.name, this.job){
count++;
}
Person.doctor(this.name, {this.job = "doctor"});
}
Another very useful feature of static class methods is that you can make them asynchronous, i.e. wait for full initialisation in case this depends on some asynchronous operation:
Future<double> getCurrentPrice(String ticker) async {
double price;
// for example, fetch current price from API
price = 582.18;
return price;
}
class Stock {
String ticker;
double currentPrice=0.0;
Stock._(this.ticker);
static Future<Stock> stockWithCurrentPrice(String ticker) async {
Stock stock = Stock._(ticker);
stock.currentPrice = await getCurrentPrice (ticker);
return stock;
}
}
void main() async {
Stock stock = await Stock.stockWithCurrentPrice('AAPL');
print ('${stock.ticker}: ${stock.currentPrice}');
}
Another benefit of the distinction between named constructor and static function is that in the documentation generated the function will be either filed in the construction section or the methods section, which further makes it's intentions clearer to the reader.
A person looking for a constructor in the constructor section of the documentation will easily discover the named constructors as opposed to having to also dig through the static functions section too.

Dart can you overload the assignment operator?

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 :)

Creating an object passing a lambda expression to the constructor

I have an object with a number of properties.
I want to be able to assign some of these properties when I call the constructor.
The obvious solution is to either have a constructor that takes a parameter for each of the properties, but that's nasty when there are lots. Another solution would be to create overloads that each take a subset of property values, but I could end up with dozens of overloads.
So I thought, wouldn't it be nice if I could say..
MyObject x = new MyObject(o => o.Property1 = "ABC", o.PropertyN = xx, ...);
The problem is, I'm too dim to work out how to do it.
Do you know?
C# 3 allows you to do this with its object initializer syntax.
Here is an example:
using System;
class Program
{
static void Main()
{
Foo foo = new Foo { Bar = "bar" };
}
}
class Foo
{
public String Bar { get; set; }
}
The way this works is that the compiler creates an instance of the class with compiler-generated name (like <>g__initLocal0). Then the compiler takes each property that you initialize and sets the value of the property.
Basically the compiler translates the Main method above to something like this:
static void Main()
{
// Create an instance of "Foo".
Foo <>g__initLocal0 = new Foo();
// Set the property.
<>g__initLocal0.Bar = "bar";
// Now create my "Foo" instance and set it
// equal to the compiler's instance which
// has the property set.
Foo foo = <>g__initLocal0;
}
The object initializer syntax is the easiest to use and requires no extra code for the constructor.
However, if you need to do something more complex, like call methods, you could have a constructor that takes an Action param to perform the population of the object.
public class MyClass
{
public MyClass(Action<MyClass> populator)
{
populator.Invoke(this);
}
public int MyInt { get; set; }
public void DoSomething()
{
Console.WriteLine(this.MyInt);
}
}
Now you can use it like so.
var x = new MyClass(mc => { mc.MyInt = 1; mc.DoSomething(); });
Basically what Andrew was trying to say is if you have a class (MyObject for eg) with N properties, using the Object Initializer syntax of C# 3.0, you can set any subset of the N properties as so:
MyObject x = new MyObject {Property1 = 5, Property4 = "test", PropertyN = 6.7};
You can set any of the properties / fields that way./
class MyObject
{
public MyObject(params Action<MyObject>[]inputs)
{
foreach(Action<MyObject> input in inputs)
{
input(this);
}
}
}
I may have the function generic style wrong, but I think this is sort of what you're describing.