Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello, I'm new to Flutter/Dart. When I take an instance of a class and try to use a method in it, I getting below error.How can i use method from instance class with new class name? Thanks.

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


My example below:
Dart
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().
}


What I have tried:

I dont have any idea? I can use as Data.read() but i think this is not right way, if i use instance with parent name in a new class.
Posted
Updated 14-Feb-24 10:56am
v5

1 solution

I found solution on flutter/dart discord channel.
I should have marked the method of the new class as "late".
I marked late then working now.

Dart
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
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900