0
votes

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;
 }
}
2

2 Answers

0
votes

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!

0
votes

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

}