【问题标题】:Flutter: How to Access Variable inside another Method?Flutter:如何在另一个方法中访问变量?
【发布时间】:2020-10-15 00:33:39
【问题描述】:

我在同一个类中有这两种方法,我想在第二种方法中访问一个变量。在 C# 中我们只是将它设置为公共变量.. 但是 Dart 和 Flutter 呢.. 如何在 play 方法中访问这个变量 'hours'。

这是我尝试过的方式,但它告诉我它无法识别小时变量。

问题是 'hours' 变量是最终变量,不能在类级别声明,因为它需要初始化,我只想在学习方法中初始化它

class Student{
Future study(){
   final hours = 5;
 }

void play(){
    int playhours = study().hours +2;
 }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您不能只将您在函数中定义的变量设为全局变量。我通常做的是,如果我需要访问将在我的类的另一个函数中设置的变量,那么我将在函数外部定义变量,并在以后需要时调用它。对于你的例子,我会这样做:

    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() 函数中的值!

    【讨论】:

      【解决方案2】:

      简单地这样做:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-15
        • 1970-01-01
        • 1970-01-01
        • 2014-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-06
        相关资源
        最近更新 更多