Reputation: 69
I am new to dart and am having issues storing data in a class. I know how to create instances but I then want to store each instance into a map that I can easily access. Here is my code below...
class myCar{
var myMapOfCars = new Map(); // I wanted this to be a class level variable that I can continuously add or remove from.
String carName; // Instance
myCar({this.carName});
addInfoToMap() {
// Some logic to increment the index or create the index the
myMapOfCars[theKey] = this.carName; // This should be the class variable.
}
}
Every time I call "addInfoToMap", the "myMapOfCars" instance is reinitialized and empty again. I wanted to add/append into the map so I can have as many cars in there as I want. I am open to other solutions as well, I come from Swift and I know you can do it in Swift. It just makes everything really clean.
Thanks for your help!!
Upvotes: 0
Views: 9013
Reputation: 6737
The documentation "Class variables and methods" would be appropriate for this.
Static variables
Static variables (class variables) are useful for class-wide state and constants:class Queue { static const initialCapacity = 16; // ··· } void main() { assert(Queue.initialCapacity == 16); }
Static variables aren’t initialized until they’re used.
Static methods
Static methods (class methods) don’t operate on an instance, and thus don’t have access to this. They do, however, have access to static variables. As the following example shows, you invoke static methods directly on a class:import 'dart:math'; class Point { double x, y; Point(this.x, this.y); static double distanceBetween(Point a, Point b) { var dx = a.x - b.x; var dy = a.y - b.y; return sqrt(dx * dx + dy * dy); } } void main() { var a = Point(2, 2); var b = Point(4, 4); var distance = Point.distanceBetween(a, b); assert(2.8 < distance && distance < 2.9); print(distance); }
You can use static methods as compile-time constants. For example, you can pass a static method as a parameter to a constant constructor.
As an additional reference, you can also visit this blog.
Upvotes: 0