Can anyone please help me? I don't understand why my code is giving an error.
int add (int n1, int n2){
n1 n2;
}
void main() {
int step1Result = add(n1: 5, n2: 9);
print(step1Result);
}
CodePudding user response:
You've crated positioned constructor but passing data as named constructor.
try like
int step1Result = add( 5, 9);
Or to create positioned constructor
int add({required int n1, required int n2}) {
return n1 n2;
}
void main() {
int step1Result = add(n1: 5, n2: 9);
print(step1Result);
}
Check more about using-constructors
CodePudding user response:
You need to add the return statement.
int add (int n1, int n2){
return n1 n2;
}
CodePudding user response:
add(n1: 5, n2: 9)
for calling like this , you need to use -> {} on function , like below
int add ({int n1, int n2}){
return n1 n2;
}
CodePudding user response:
Dart has two types of parameters: Required and optional parameters, in optional there are two types named and positional.
In the named ones you specify n1: 5, n2: 9 like you have done, and in positional you don't need to add the parameter name.
In your case you can choose any one of the below :
- Required parameter (positional) :
int add (int n1, int n2){
n1 n2;
}
void main() {
int step1Result = add(5,9);
print(step1Result);
}
- Optional parameter (positonal) :
int add (int n1, int n2){
n1 n2;
}
void main() {
int step1Result = add([5,9]);
print(step1Result);
}
- Optional parameter (named):
int add ({int n1, int n2}){
n1 n2;
}
void main() {
int step1Result = add(n1: 5, n2: 9);
print(step1Result);
}
(Although named parameters are a kind of optional parameter, you can annotate them with required to indicate that the parameter is mandatory)