setting and accessing class variables in dart not working as expected

Viewed 272

I have a class in dart

class myClass {

String var1 = '';

void method1 {
  var1 = "Test"
}

void method2 {
  print(this.var1);
}

Why does the print of the second method not print anything? What is it I am missing here?

3 Answers

depends on how you call it

myClass myclass = myClass();
myclass.method1();
myclass.method2();

this got to work fine

your code have some problems! you should provide methodName() parenthesis after method name in class definition:

  class MyClass {

String var1 = '';

void method1() {
  this.var1 = "Test";
}

void method2() {
  print(this.var1);
}
}

then you can create an object as follow:

myClass t = new myClass();
  
  print(t.var1);
  t.method1();
  t.method2();

It is printing but it is printing an empty string ("").
Your code has too many mistakes, you have to add parasynthesis() after the function name.

secondly you have to call the method1 function first that will set the var1 value to "test". after that call method2. Here is the code, I'm attaching.

class myClass {

String var1 = '';

void method1() {
  var1 = "Test";
}

void method2 (){
  print(this.var1);
}

}

void main(){
  var obj = myClass();
  obj.method1();
  obj.method2();
}
Related