英文:
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();
  }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论