0

Pretty new to programming and very new to dart/flutter.

The properties of an object of one class are needed to construct an object of another class. I try constructing to the object of the independent class first and defining the property, then follow by constructing an object of the second class and passing it's constructor the property from first class as parameter. I get the following error,

Error Message: Instance member 'x' can't be accessed in an initializer

EDIT: typo in 3rd line of code has been changed

Example:

    void main(){
      Class1 instanceOfClass1 = Class1(property_A: 10);
      Class2 instanceOfClass2 = Class2(property_B: instanceOfClass1.property_A)
    }
    
    class Class1 {
      var property_A;
      
      Class1({required this.property_A});
    }
    
    class Class2 {
      var property_B;
      
      Class2({required this.property_B});
    }
  • Just wondering if anyone can help explain whats happening here and any possible solutions or alternative methods for constructing an object of one class based off of the properties of an object of another class. – XavierRenegadeAngel Mar 17 '22 at 06:42

1 Answers1

0

property_A is not a static variable hence it can't be accessed with Class1.property_A

It is rather a field in an object/instance of Class1

Access it with instanceOfClass1.property_A instead. Like so:

 void main(){
      Class1 instanceOfClass1 = Class1(property_A: 10);
      Class2 instanceOfClass2 = Class2(property_B: instanceOfClass1.property_A);
    }
    
    class Class1 {
      var property_A;
      
      Class1({required this.property_A});
    }
    
    class Class2 {
      var property_B;
      
      Class2({required this.property_B});
    }
Josteve
  • 11,459
  • 1
  • 23
  • 35