【问题标题】:How to set a property of a base class when constructing an inherited widget?构造继承的小部件时如何设置基类的属性?
【发布时间】:2021-03-22 10:11:09
【问题描述】:

我想创建一个名为HomeAppBar 的继承AppBar,它继承自CommonAppBar,它继承自AppBar。 CommonAppBar 设置背景为紫色,HomeAppBar 设置标题为Hourlogger

class CommonAppBar extends AppBar {
  CommonAppBar() : super(backgroundColor: Colors.purple);
}

class HomeAppBar extends CommonAppBar {
  HomeAppBar() : super(title: Text("Hourlogger"));
}

编译器怎么说

未定义命名参数“title”。 尝试将名称更正为现有命名参数的名称,或使用名称“title”定义命名参数。

我的印象是 CommonAppBar 应该从 AppBar 继承 title。我应该如何在我的自定义AppBar 中设置title?

【问题讨论】:

  • super(title: Text(...)) 等于 CommonAppBar()。我想您已经知道如何在构造函数中添加命名参数。只是不要忘记通过super(...) 将title 属性从CommonAppBar 传递给它的父类。

标签: flutter dart flutter-layout


【解决方案1】:
class CommonAppBar extends AppBar {
  final Widget title;
  CommonAppBar({this.title}) : super(backgroundColor: Colors.purple, title: title);
}

class HomeAppBar extends CommonAppBar {
 HomeAppBar() : super(title: Text("Hourlogger"));
}

这应该在你首先从构造函数中获取标题参数并将其传递给 super 的地方工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多