我试图根据输入值对某些属性进行赋值。该值在小部件的生命周期内保持不变。因此,我使用了Stateless
小部件。但是,我无法在构造函数中为属性分配值。
class InOrOut extends StatelessWidget {
final Condition condition;
final bool isIconVisible;
final Color backgroudColor;
final Color foregrounndColor;
InOrOut({Key key, this.condition, this.isIconVisible}) : super(key: key) {
switch (condition) {
case Condition.IN:
backgroudColor = Colors.green[100];
foregrounndColor = Colors.green[100];
isIconVisible = false
break;
case Condition.ABSENT:
backgroudColor = Colors.grey[300];
foregrounndColor = Colors.green[100];
isIconVisible = true;
break;
case Condition.OUT:
backgroudColor = Colors.red[100];
foregrounndColor = Colors.green[100];
isIconVisible = false;
break;
default:
backgroudColor = Colors.red[100];
foregrounndColor = Colors.green[100];
isIconVisible = false;
}
}
尝试将值分配给prop时会出现以下错误:
'foregrounndColor'不能用作setter,因为它是final的。尝试找到另一个setter或将'foregrounndColor'设置为non-final。
如果我删除
final
,那么我不能在Stateless
小部件内使用它。最后,因为这个问题我应该改为使用
Stateful
小部件吗?
Condition
),而Condition
是最终的,所以我仍然认为在构造函数中声明它们为late
并进行初始化的方法是可接受的。你为什么认为这是错误的呢? - maganapfinal
,那么它绝对是不必要的。如果你可以轻松地避免不必要的 Stateful widgets、不必要的重建以及许多其他不必要的“小”事情,长期来看,这将有助于避免性能问题。所以,如果你可以保持 Stateless,为什么不呢?我想这是遵循最佳实践的问题。 - maganap