我在同一个类中有这两个方法,并且我想访问第二个方法中的一个变量。在C#中,我们只需将其设置为公共变量。但是Dart和Flutter呢..如何在play方法中访问这个变量'hours‘。
这是我尝试过的方法,但它告诉我它不能识别小时变量。
问题是,‘小时’变量是最终变量,不能在类级别声明,因为它需要初始化,而我只想在study方法中初始化它
class Student{
Future study(){
final hours = 5;
}
void play(){
int playhours = study().hours +2;
}
}发布于 2020-06-25 03:07:32
您不能只将您在函数中定义的变量设为全局变量。我通常做的是,如果我需要访问一个变量,该变量将在我的类的另一个函数中设置,那么我将在函数外部定义该变量,并在以后需要时调用它。对于您的示例,我将执行以下操作:
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();
}你可以做的另一件事是在你的study()函数中return这个值!
发布于 2021-08-31 13:29:27
简单地这样做就可以了:
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
}
}然后从main函数调用它,如下所示:
void main() {
Student().play();
}https://stackoverflow.com/questions/62560316
复制相似问题