“私有变量 ‘命名参数不能以下划线开头’ 为什么会出错?”

huangapple go评论90阅读模式
英文:

Why is private variable 'Named parameters cannot begin with an underscore.' gets the error?

问题

这段代码出错的原因是因为在构造函数 AppBarTitleColor 中使用了 super.key,但在 StatelessWidget 中并没有定义 key 参数。解决方法是移除 super.key

修改后的代码应如下所示:

class AppBarTitleColor extends StatelessWidget {
  final Color _appBarTitleColor;
  const AppBarTitleColor({this._appBarTitleColor = Colors.black});

  @override
  Widget build(BuildContext context) {
    return const AppBarTitleColor();
  }
}

这样就移除了无法识别的 super.key,代码应该能够正常工作了。

英文:

Can you explain why this code gives an error and the solution? appbar header color should be accessible only from this file

class AppBarTitleColor extends StatelessWidget {
  final Color _appBarTitleColor;
  const AppBarTitleColor({super.key, this._appBarTitleColor = Colors.black});

  @override
  Widget build(BuildContext context) {
    return const AppBarTitleColor();
  }
}

I thought it might be related to 'final' or 'const' but my changes didn't work

答案1

得分: 1

你不能直接实例化一个私有变量(带下划线)

你需要按照以下方式实现它:

class AppBarTitleColor extends StatelessWidget {
  final Color _appBarTitleColor;

  const AppBarTitleColor({
    super.key,
    Color appBarTitleColor = Colors.black,
  }) : _appBarTitleColor = appBarTitleColor;

  @override
  Widget build(BuildContext context) {
    return const AppBarTitleColor();
  }
}
英文:

You cannot instantiate a private variable (with underscore) directly.

You need to implement it like below:

class AppBarTitleColor extends StatelessWidget {
  final Color _appBarTitleColor;

  const AppBarTitleColor({
    super.key,
    Color appBarTitleColor = Colors.black,
  }) : _appBarTitleColor = appBarTitleColor;

  @override
  Widget build(BuildContext context) {
    return const AppBarTitleColor();
  }
}

huangapple
  • 本文由 发表于 2023年6月30日 02:58:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定