我在同一个类中有这两个方法,我想在第二个方法中访问一个变量。在C#中,我们只是将其设置为公共变量..但是Dart和Flutter呢..如何在play方法中访问此变量“小时”。
这是我尝试过的方法,但它告诉我它无法识别小时数变量。
问题是'hours'变量是最终变量,无法在课程级别进行声明,因为它需要初始化,而我只想在学习方法内部对其进行初始化
class Student{
Future study(){
final hours = 5;
}
void play(){
int playhours = study().hours +2;
}
}
答案 0 :(得分:0)
您不能仅仅使您在函数内部定义的全局变量成为全局变量。我通常要做的是,如果我需要访问将在类的另一个函数中设置的变量,那么我将在函数外部定义变量,并在以后需要时调用它。对于您的示例,我将执行以下操作:
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
}
}
然后在调用它时:
void main() {
Student student = Student();
//student.study(); If you use it separately
student.play();
}
您可以做的另一件事是在return
函数中study()
的值!