When I try to create a constructor in dart like Student(this._name)
it doesn't work with private variables.
I have already tried using setters but it doesn't work either.
class Student{
var _id;
var _name;
Student(this.id, this.name);
void set id(int id) => _id = id;
void set name(String name) => _name = name;
}
In Javascript there's no specific way to make variables private in a Constructor function. If a variable is genuinely private, meaning it cannot be accessible from the outside.
A constructor can be made private by using (_) underscore operator which means private in dart. class FooBar extends Foo { FooBar() : super. _(); // This will give compile time error. }
If an identifier starts with an underscore _ , it's private to its library. Libraries not only provide APIs, but are a unit of privacy: identifiers that start with an underscore _ are visible only inside the library.
In Dart, privacy is at the library level, not the class level. You can access a class's private members from code outside of that class as long as that code is in the same library where the class is defined. (In Java terms, Dart has package private.
This is not supported because it would expose private implementation to the outside.
If you'd rename var _id;
to var _userId;
you would break code that uses your class just by renaming a private field.
See instead the comment below my answer.
class Student{
var _id;
var _name;
Student({this._id, this._name}); // error
void set id(int id) => _id = id;
void set name(String name) => _name = name;
}
The alternative
class Student{
var _id;
var _name;
Student({int id, String name}) : _id = id, _name = name;
void set id(int id) => _id = id;
void set name(String name) => _name = name;
}
You can use this notation
class Student {
String _id;
String _name;
Student({required String id, required String name})
: _id = id,
_name = name;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With