Young
Young

Reputation: 1091

How to use a variable from a different class

I have a rather simple question. How can I use variables from different classes in dart?

class ContainsVariable {

  var variable = 1;

}

class DoesNotContainVariable {

  var useVariable = variable + 1; // This gives me an error saying:
                                  // Undefined name 'variable' 

}

Upvotes: 1

Views: 109

Answers (1)

bradib0y
bradib0y

Reputation: 1089

Having their own scope is a very fundamental feature of classes in Object Oriented Programming, corresponding to OOP principles.

Also note that from your code, it seems that you have not properly understood the idea of instantiation in Object Oriented Programming, since you are trying to set an instance variable without instantiating the class. I highly suggest to look into this topic to gain more understanding.

That being said, there are most definitely many ways to achieve what you want. Since your code sample is very general, I'm not exactly sure what you are trying to do, so I'll provide 2 examples, which might be useful:

Option 1 - static member variable

You can make a static (class level) member, which will be the same for all objects.


class ContainsVariable {

  static var variable = 1;

}

class DoesNotContainVariable {

  var useVariable = ContainsVariable.variable + 1; // here, you are using a
                                                   // static (class) variable, 
                                                   // not an instance variable. 
                                                   // That is why you are using 
                                                   // the class name.                                 

}

Option 2 - instantiation

You can instantiate the class - by creating an object of that class - and access the member of that object. Notice that there is no static statement here.


class ContainsVariable {

  var variable = 1;

}

class DoesNotContainVariable {

  var instanceOfContainsVariable;
  var useVariable; 

  DoesNotContainVariable(){ // this is a constructor function
    var instanceOfContainsVariable = new ContainsVariable();
    useVariable = instanceOfContainsVariable.variable + 1;
  }

}

Upvotes: 1

Related Questions