Reputation: 63
Why i have an error in this case :
class Person {
Person({name,age});
var name,age = 5;
name = "wael";
void Xprint()=>print('$name is $age years old');
}
main () {
var x = Person();
x.Xprint();
}
error
1.dart:6:3: Error: Variables must be declared using the keywords 'const', 'final', 'var' or a type name. Try adding the name of the type of the variable or the keyword 'var'. name = "wael"; ^^^^ 1.dart:6:3: Error: 'name' is already declared in this scope. name = "wael"; ^^^^ 1.dart:5:7: Context: Previous declaration of 'name'. var name,age = 5; ^^^^ 1.dart:7:26: Error: Can't use 'name' because it is declared more than once. void Xprint()=>print('$name is $age years old'); ^
Upvotes: 1
Views: 1423
Reputation: 71828
I'm not sure what you are trying to achieve here, but let me try to explain what is happening.
If you were declaring local variables (inside a function), then your approach would be sound:
void someFunction() {
var name, age = 5; // Declaration of two local variables, initialize one of them.
name = "wael"; // Statement assigning a value to `name`.
void xprint() => print('$name is $age years old'); // Function declaration
xprint(); // Statement performing a function call.
}
However, you are declaring a class:
class Person {
var name, age = 5; // Declaration of two instance variables.
Person({name, age}); // constructor (needs more work);
name = "wael"; // .... this is invalid. Statements are not allowed here.
void Xprint()=>print('$name is $age years old'); // Instance method declaration.
}
So the problem is that name = "wael";
is not allowed to occur where it does. Statements are only allowed inside functions, not as part of class declarations.
It's not clear what you want to do. So, let's declare the Person
class the way I'd normally do it:
class Person {
String name;
int age;
Person({this.name = "wael", this.age = 5}); // Parameters initialize variables directly.
void xprint() {
print("$name is $age years old");
}
}
This class has "wael" as default value for the name and "5" as default value for the age, but uses the parameter instead if one is supplied.
(I'd probably not have a default value for name
or age
, but let's assume it makes sense in this case).
Upvotes: 1
Reputation: 1202
You can not have any instruction in open place of a class
. Any instruction must be inside a method. Yo can do this:
class Person {
Person({name,age});
var name= "wael",age = 5; // assign default value while declartion
void Xprint()=>print('$name is $age years old');
}
main () {
var x = Person();
x.Xprint();
}
or set the default value on constructor
class Person {
Person({this.name= "wael",age});
var name,age = 5;
void Xprint()=>print('$name is $age years old');
}
main () {
var x = Person();
x.Xprint();
}
Upvotes: 2