简体   繁体   English

无法在 Dart 的构造函数中调用 class 方法 class

[英]Unable to call class method in the constructor of a Dart class

I am new to Dart programming.我是 Dart 编程的新手。 Need help in updating the List "items" before instantiating the super class.在实例化超级 class 之前需要帮助更新列表“项目”。

import 'package:flutter/material.dart'; import '../util/color_constants.dart';

class CustomBottomNavigatorBar extends BottomNavigationBar{

  final List<BottomNavigationBarItem> items;

  CustomBottomNavigatorBar(
      this.items,   ): super(backgroundColor: ColorConstants.facebook_blue,items: updateListWithDefaultIcons(items));

  List<BottomNavigationBarItem> updateListWithDefaultIcons(){
    items.add(BottomNavigationBarItem(
      label: 'Settings',
      icon: Icon(Icons.settings),
      tooltip: 'Settings',
      backgroundColor: ColorConstants.white,));
    items.add(BottomNavigationBarItem(
      label: 'Profile',
      icon: Icon(Icons.man),
      tooltip: 'Profile',
      backgroundColor: ColorConstants.white,));
    return items;   } }

Here is the error that Dart throws up while compiling the code这是Dart在编译代码时抛出的错误

The instance member 'updateListWithDefaultIcons' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression

You can use variable instead of method updateListWithDefaultIcons and pass default on items.您可以使用变量而不是方法updateListWithDefaultIcons并传递项目的默认值。 and it is recommended not to create items variable that is coming from parent.并且建议不要创建来自父项的items变量。

class CustomBottomNavigatorBar extends BottomNavigationBar {
  final List<BottomNavigationBarItem> items_;

  CustomBottomNavigatorBar({
    Key? key,
    this.items_ = _updateListWithDefaultIcons,
  }) : super(
          key: key,
          backgroundColor: Colors.cyanAccent,
          items: items_,
        );

  static const List<BottomNavigationBarItem> 
                    _updateListWithDefaultIcons = [
                         BottomNavigationBarItem(...)
                         .... ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM