Reputation: 9859
I am learning Dart. I did not found any answer for my question in docs. Can I create and use class without constructor, or I can get some problem with it later?
class MyClass {
String name;
int age;
}
Upvotes: 1
Views: 1845
Reputation: 884
Sure, you don’t have to use a constructor in your class, but that takes away your ability to create an immutable class with final fields plus you can’t set your values instantly. There will always be a default constructor for your class without you defining it. With your current code you’d have to do something like
final myVar = MyClass();
myVar.name = "John";
myVar.age = 24;
Upvotes: 2
Reputation: 71693
You can create an use a class with no explicit constructor.
If you do not write any constructor, you will be given a default constructor of MyClass() : super();
. That only works if
Object
satisfies.)It means that your get a public generative constructor, which allows others to extend your class. If you want to prevent that, you can change that to a public factory/private generative constructor pair:
factory C() => C._();
C._();
Upvotes: 5