Initialize a final variable in a constructor in Dart. Two ways but only one of them work? [duplicate] - flutter

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

Related

Dart convert data to custom class

I have a function Future<T?> getDocById<T>(String id) aysnc {}, it gets the data from web and return the value with type T. How can I convert any incoming data from web to a given type?
use case - class User{ String name; User(this.name);}
now, await getDocById<User>() how can I convert the data to type User inside getDocById function? in another case - getDocById<Boo> it should get data from web and convert it to Boo and return
Since I just answered a similar question I am copying the code into here. However, if you have an unknown T incoming, you need to distinguish cases based on what is incoming. Without this you want be able to convert a bool or int into a String name.
Create a method in one of the classes
class A {
A(this.a);
final int a;
B toB() {
return B(
b: a,
}
}
class B {
B(this.b);
final int b;
}
To be used like final bInstance = aInstance.toB(); meaning you declared somewhere aInstance = A(1);

(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.

Flutter: How to Access Variable inside another Method?

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();
}

C++ Accessing variables in a function in one class from a different class

I'm trying to code a program with multiple classes such the one of the class reads the variables from a text file and the other classes use these variables for further processing.
The problem I'm facing is that I'm having trouble passing the variables from one class to another class, I did try "friend" class and also tried to use constructors but failed
to get the desired output.
The best I could do was
suppose I have class 1 and class 2, and I have a variable "A=10" declared and initialised in class 1, with the help of constructor I inherit it in class 2;
when I print it in class 1, it gives a correct output as 10 but when I print it in class 2 it gives an output as 293e30 (address location)
Please guide me on how to this.
Class1
{
public:
membfunc()
{
int A;
A = 10;
}
}
Class2
{
public:
membfunc2()
{
int B;
B = A + 10;
}
membfunc3()
{
int C, D;
C = A + 10;
D = B + C;
}
}
If i print variables, i expect to get
A = 10, B = 20, C = 20, D = 40
But what I get is
A = 10, B=(252e30) + 10
I think your problem was that you were defining local variables in your member functions, instead of creating member variables of a class object.
Here is some code based on your sample to demonstrate how member variables work:
class Class1
{
public:
int A;
void membfunc()
{
A=10;
}
};
class Class2
{
public:
int B;
int C;
int D;
void membfunc2(Class1& class1Object)
{
B = class1Object.A + 10;
}
void membfunc3(Class1& class1Object)
{
C = class1Object.A + 10;
D = B + C;
}
};
(Full code sample here: http://ideone.com/cwZ6DM.)
You can learn more about member variables (properties and fields) here: http://www.cplusplus.com/doc/tutorial/classes/.

What are function typedefs / function-type aliases in Dart?

I have read the description, and I understand that it is a function-type alias.
A typedef, or function-type alias, gives a function type a name that you can use when declaring fields and return types. A typedef retains type information when a function type is assigned to a variable.
http://www.dartlang.org/docs/spec/latest/dart-language-specification.html#kix.yyd520hand9j
But how do I use it? Why declaring fields with a function-type? When do I use it? What problem does it solve?
I think I need one or two real code examples.
A common usage pattern of typedef in Dart is defining a callback interface. For example:
typedef void LoggerOutputFunction(String msg);
class Logger {
LoggerOutputFunction out;
Logger() {
out = print;
}
void log(String msg) {
out(msg);
}
}
void timestampLoggerOutputFunction(String msg) {
String timeStamp = new Date.now().toString();
print('${timeStamp}: $msg');
}
void main() {
Logger l = new Logger();
l.log('Hello World');
l.out = timestampLoggerOutputFunction;
l.log('Hello World');
}
Running the above sample yields the following output:
Hello World
2012-09-22 10:19:15.139: Hello World
The typedef line says that LoggerOutputFunction takes a String parameter and returns void.
timestampLoggerOutputFunction matches that definition and thus can be assigned to the out field.
Let me know if you need another example.
Dart 1.24 introduces a new typedef syntax to also support generic functions. The previous syntax is still supported.
typedef F = List<T> Function<T>(T);
For more details see https://github.com/dart-lang/sdk/blob/master/docs/language/informal/generic-function-type-alias.md
Function types can also be specified inline
void foo<T, S>(T Function(int, S) aFunction) {...}
See also https://www.dartlang.org/guides/language/language-tour#typedefs
typedef LoggerOutputFunction = void Function(String msg);
this looks much more clear than previous version
Just slightly modified answer, according to the latest typedef syntax, The example could be updated to:
typedef LoggerOutputFunction = void Function(String msg);
class Logger {
LoggerOutputFunction out;
Logger() {
out = print;
}
void log(String msg) {
out(msg);
}
}
void timestampLoggerOutputFunction(String msg) {
String timeStamp = new Date.now().toString();
print('${timeStamp}: $msg');
}
void main() {
Logger l = new Logger();
l.log('Hello World');
l.out = timestampLoggerOutputFunction;
l.log('Hello World');
}
Typedef in Dart is used to create a user-defined function (alias) for other application functions,
Syntax: typedef function_name (parameters);
With the help of a typedef, we can also assign a variable to a function.
Syntax:typedef variable_name = function_name;
After assigning the variable, if we have to invoke it then we go as:
Syntax: variable_name(parameters);
Example:
// Defining alias name
typedef MainFunction(int a, int b);
functionOne(int a, int b) {
print("This is FunctionOne");
print("$a and $b are lucky numbers !!");
}
functionTwo(int a, int b) {
print("This is FunctionTwo");
print("$a + $b is equal to ${a + b}.");
}
// Main Function
void main() {
// use alias
MainFunction number = functionOne;
number(1, 2);
number = functionTwo;
// Calling number
number(3, 4);
}
Output:
This is FunctionOne
1 and 2 are lucky numbers !!
This is FunctionTwo
3 + 4 is equal to 7
Since dart version 2.13 you can use typedef not only with functions but with every object you want.
Eg this code is now perfectly valid:
typedef IntList = List<int>;
IntList il = [1, 2, 3];
For more details see updated info:
https://dart.dev/guides/language/language-tour#typedefs
https://www.tutorialspoint.com/dart_programming/dart_programming_typedef.htm
typedef ManyOperation(int firstNo , int secondNo); //function signature
Add(int firstNo,int second){
print("Add result is ${firstNo+second}");
}
Subtract(int firstNo,int second){
print("Subtract result is ${firstNo-second}");
}
Divide(int firstNo,int second){
print("Divide result is ${firstNo/second}");
}
Calculator(int a,int b ,ManyOperation oper){
print("Inside calculator");
oper(a,b);
}
main(){
Calculator(5,5,Add);
Calculator(5,5,Subtract);
Calculator(5,5,Divide);
}