Is there a way to set a constructor optional param?
I mean something like:
User.fromData(this._name,
this._email,
this._token,
this._refreshToken,
this._createdAt,
this._expiresAt,
this._isValid,
{this.id});
It indicates that
Named option parameters can't start with an underscore.
But I need this field as private, so, I'm lost now.
This is a more general answer for future viewers.
Positional optional parameters
Wrap the optional parameter with [ ] square brackets.
class User {
String name;
int age;
String home;
User(this.name, this.age, [this.home = 'Earth']);
}
User user1 = User('Bob', 34);
User user2 = User('Bob', 34, 'Mars');
Optional parameters need to be nullable if you don't provide a default value:
class User {
String name;
int age;
String? home; // <-- Nullable
User(this.name, this.age, [this.home]);
}
Named optional parameters
Wrap the optional parameter with { } curly braces.
class User {
String name;
int age;
String home;
User(this.name, this.age, {this.home = 'Earth'});
}
User user1 = User('Bob', 34);
User user2 = User('Bob', 34, home: 'Mars');
The default for home is "Earth", but like before, if you don't provide a default then you need to change String home to String? home.
Private fields
If you need private fields then you can use [] square brackets:
class User {
int? _id;
User([this._id]);
}
User user = User(3);
or do as the accepted answer says and use an initializer list:
class User {
int? _id;
User({int? id})
: _id = id;
}
User user = User(id: 3);
Named required parameters
Named parameters are optional by default, but if you want to make them required, then you can use the required keyword:
class User {
final String name;
final int age;
final String home;
User({
required this.name,
required this.age,
this.home = 'Earth',
});
}
User user1 = User(name: 'Bob', age: 34);
User user2 = User(name: 'Bob', age: 34, home: 'Mars');
You need to use a simple parameter and initialize your private field in initializer list.
class User {
final String _id;
final String _name;
User.fromData(this._name, {required String id})
: _id = id;
}
In addition to great Suragch's answer I wanted to mention required word. You can use it for multiple constructor or function named parameters to specify required ones.
class User {
int _id;
String _firstName;
String _lastName;
User({required int id, String firstName = "", String lastName})
: _id = id, // required parameter
_firstName = firstName, // optional parameter with default value ""
_lastName = lastName; // optional parameter without default value
}
User user1 = User(id: 1);
User user2 = User(id: 2, firstName: "John");
User user3 = User(id: 3, lastName: "Snow");
Related Dart docs here.
For Dart version <= 2.10 #required is an annotation and used with the # prefix.
Related
I am working on a Flutter web app, and am using a custom class to keep track of form data. I am instantiating a new instance of the following class:
class Contact {
String name;
String relationship;
String phoneNo;
#override
String toString() {
print("""{
Name: $name,
Relation: $relationship,
Phone: $phoneNo
}""");
}
}
In my controller, once I instantiate, I am printing out the value immediately:
// Method in controller, triggered by onTap
Contact contact = Contact();
print(contact);
The output is:
{
Name: null,
Relation: null,
Phone: null
}
null
Which is causing issues later down the line, as instances of this class are being used as values of a HashMap. I have narrowed down the issue to being caused by the toString method, and when I remove it, Instance of 'Contact' is then printed out, as desired. What is the best way to handle this?
// Method in controller, triggered by onTap
Contact contact = Contact();
print(contact);
You created a new instance of Contact with no arguments that's why all the value of Contact will be null.
To assign a value there are two solutions:
1. Inside from class itself:
class Contact {
String name = 'John doe';
String relationship = 'Brother';
String phoneNo = '1234567890';
#override
String toString() {
print("""{
Name: $name,
Relation: $relationship,
Phone: $phoneNo
}""");
}
}
2.From outside of Class
for that, you have to initiate Constructor in your class
class Contact {
String name;
String relationship;
String phoneNo;
Contact(this.name, this.relationship, this.phoneNo);
//You can also choose between named parameters and positional parameters
// For named parameters Contact({this.name, and so on....})
#override
String toString() => """{
Name: $name,
Relation: $relationship,
Phone: $phoneNo
}""";
}
in this scenario you have to pass values where you create instance of class as shown here:
Contact contact = Contact('John Doe', 'brother', '123456789');
print(contact);
I have a post request from Angular.
addEmployee(Name: string, Address: string, Salary: number, CreateDate: string) {
const headers = new HttpHeaders().set('content-type', 'application/json');
const employee: EmployeeDataModel = { id: null, name: Name, address: Address, salary: Salary, createdate: CreateDate };
alert(employee);
this.http.post<{data: EmployeeDataModel}>(this.appuri + "api/employee", employee, {headers})
.subscribe((responseData) => {
employee.id = responseData.data.id;
this.employees.push(employee);
this.employeesUpdated.next([...this.employees]);
});
}
I can't read a request body in .net core backend.
[HttpPost]
public async Task<ActionResult<Employee>> AddEmployee([FromBody]Employee employee)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
dbContext.Employees.Add(employee);
await dbContext.SaveChangesAsync();
return CreatedAtAction("GetAllEmployees", new { id = employee.ID }, employee);
}
And i also have this error message in ModelState:
The JSON value could not be converted to System.Int32.
Path: $.id | LineNumber: 0 | BytePositionInLine: 10.
Can you help me please because i don't know what's wrong as i'm new to this.
Remove the id property from your request body, or set it to 0. The value null cannot be parsed to an int by the serializer.
const employee: Partial<EmployeeDataModel> = { name: Name, address: Address, salary: Salary, createdate: CreateDate };
// OR
const employee: EmployeeDataModel = { id: 0, name: Name, address: Address, salary: Salary, createdate: CreateDate };
The Partial<> is only to make sure typescript won't scream at you for ommitting the id property.
Note that setting it to a value other than 0 will mean that your DbContext will try to insert that value into the database, and unless your column in the database is not using IDENTITY (or has IDENTITY INSERT turned on), you will get an error again.
How to use a String value as a parameter in findById(), It always expecting a Long value. Iam using a domain class named Employee and I configured its id key as string. But still Employee.findById() is expecting a long value as parameter.
Please help me
My Employee.groovy
class Employee {
static hasOne = [user:User, vpn:Vpn, tenrox:Tenrox, machine: Machine, dbuser:DbUser];
static mapping = {
version false
id generator: 'assigned',type: 'string'
}
String name
String designation
String team
Long contact_no
static constraints = {
name(nullable: false,maxSize:100)
designation(nullable: true,maxSize:40)
team(nullable: true,maxSize:40)
contact_no(nullable: true,maxSize:20)
}
}
Declare your id field in the domainclass as String.
class Employee {
static hasOne = [user:User, vpn:Vpn, tenrox:Tenrox, machine: Machine, dbuser:DbUser];
static mapping = {
version false
id generator: 'assigned',type: 'string'
}
String id // Declares id as String
String name
String designation
String team
Long contact_no
static constraints = {
name(nullable: false,maxSize:100)
designation(nullable: true,maxSize:40)
team(nullable: true,maxSize:40)
contact_no(nullable: true,maxSize:20)
}
}
I have a Groovy class like so:
class Person {
String firstName
String lastName
Status status = StatusEnum.ACTIVE
}
And I'm creating an instance of it with an object initializer:
def person = new Person(
firstName: "Bob", lastName: "Yelo", status: StatusEnum.INACTIVE)
However, this doesn't modify the person's status and it remains as ACTIVE. I have to explicitly declare it:
person.status = StatusEnum.INACTIVE
Which properly sets the status. Does anyone know why I have to explicitly set it?
I'm guessing it's having something to do with the type of the field being Status rather than StatusEnum?
Declaring it like this worked as you're suggesting it should groovy console:
enum StatusEnum {
ACTIVE, INACTIVE
}
class Person {
String firstName
String lastName
StatusEnum status = StatusEnum.ACTIVE
}
def person = new Person(firstName: "Bob", lastName: "Yelo", status: StatusEnum.INACTIVE)
assert StatusEnum.INACTIVE == person.status
I am currently working on a grails application. I have two command objects (AccountInfoCommand and EducInfoCommand) in a controller. On my EducInfoCommand, I wanted to check if the yearGraduated property is earlier than the set birthDate(a property of AccountInfoCommand) on its validator constraints. How will I do that?
This is my code for my AccountInfoCommand:
class AccountDetailsCommand implements java.io.Serializable {
String username
String password
String confirmPassword
String emailAddress
Date birthDate
}
This is my code for EducInfoCommand:
class EducInfoCommand implements java.io.Serializable {
Integer graduated
EducationLevel educationLevel
String schoolName
String yearGraduated
String honorsReceived
}
static constraints = {
yearGraduated nullable: false, maxSize:4, blank: false, matches: /([0-9]*)/,
validator: {
Date.parse('yyyy',it) <= new Date() ? true : false
}
}
Please help!
Thanks!
You need some reference to which AccountDetails the EducInfo is for. For example, if you added a username field to the EducInfoCommand you could look up the account details from that (assuming there is an AccountDetails gorm object which is similar to the command object):
class EducInfoCommand implements java.io.Serializable {
String yearGraduated
String username
// ...
}
static constraints = {
yearGraduated nullable: false, maxSize:4, blank: false, matches: /([0-9]*)/,
validator: { val, obj ->
Date.parse('yyyy',val) > AccountDetails.findByUsername(obj.username).birthDate
}
}