如何使用具有新类名的实例类中的方法?


你好,我是 Flutter/Dart 的新手。 当我获取类的实例并尝试使用其中的方法时,出现以下错误。如何使用具有新类名的实例类中的方法? 谢谢。

"The instance member 'newData' can't be accessed in an initializer.
Try replacing the reference to the instance member with a different expression"

我的例子如下:

class Data {
    String read() {
        return "";
    }
}

class Data2 {
    var newData= Data(); // I took instance from the Data class.
    String readData = newData.read(); //Here it gives the above error. I want to use it as newData.read(), not Data.read().
}

我尝试过的:

我不知道吗? 我可以使用 as Data.read() 但我认为如果我在新类中使用具有父名称的实例,这不是正确的方法。

解决方案1

我在 flutter/dart 不和谐频道上找到了解决方案。
我应该将新类的方法标记为“late”。
我当时标记得很晚,现在正在工作。

class Data {
    String read() {
        return "";
    }
}

class Data2 {
    var newData= Data(); // I took instance from the Data class.
   late String readData = newData.read(); // I can using as newData.read() now
}

コメント

タイトルとURLをコピーしました