我不确定你在这里想要达到什么目的,但让我试着解释一下发生了什么。
如果您要声明 local 变量(在函数内部),那么您的方法将是合理的:
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.
}
然而,你声明了一个类:
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.
}
所以问题是name = "wael"; 不允许出现在它出现的地方。语句只能在函数内部使用,不能作为类声明的一部分。
不清楚你想要做什么。所以,让我们以我通常这样做的方式声明Person 类:
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");
}
}
此类将“wael”作为名称的默认值,将“5”作为年龄的默认值,但如果提供了参数,则使用该参数。
(我可能没有name 或age 的默认值,但我们假设它在这种情况下有意义)。