【解決方法】インスタンスクラスのメソッドを新しいクラス名で使用するにはどうすればよいですか?


こんにちは、私は 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().
}

私が試したこと:

何も考えてないんですか? Data.read() として使用できますが、新しいクラスで親名を持つインスタンスを使用する場合、これは正しい方法ではないと思います。

解決策 1

Flutter/Dart Discord チャンネルで解決策を見つけました。
新しいクラスのメソッドを「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をコピーしました