Flutter-覆盖CupertinoTabBar

时间:2018-10-15 19:53:27

标签: dart flutter

我目前正在尝试通过使自己的类扩展它并覆盖“ build”方法来自定义CupertinoTabBar小部件。我当前的代码与此类似:

class CustomTabBar extends CupertinoTabBar {
  CustomTabBar(
    Key key,
    @required List<BottomNavigationBarItem> items,
    ValueChanged<int> onTap,
    int currentIndex = 0,
    Color backgroundColor = _kDefaultTabBarBackgroundColor,
    Color activeColor = CupertinoColors.activeBlue,
    Color inactiveColor = CupertinoColors.inactiveGray,
    double iconSize = 30.0,
  ) : assert(items != null),
      super(items: items, onTap: onTap, currentIndex: currentIndex, 
        backgroundColor: backgroundColor, activeColor: activeColor, 
        inactiveColor: inactiveColor, iconSize: iconSize);

  @override
  Widget build(BuildContext context) {
    //build logic for the custom bar
  }
}

但是,当我运行该应用程序时,将调用CupertinoTabBar构建方法,而不是CustomTabBar构建方法。换句话说,我的课程没有覆盖CupertinoTabBar的构建。

我在这里做错什么了吗?之所以这样做,是因为我使用CupertinoTabScaffold为每个选项卡保留单独的导航器,而CupertinoTabScaffold的tabBar参数仅接受CupertinoTabBar。

2 个答案:

答案 0 :(得分:2)

您需要覆盖 copyWith 方法。

class CustomTabBar extends CupertinoTabBar {
  CustomTabBar(
    Key key,
    @required List<BottomNavigationBarItem> items,
    ValueChanged<int> onTap,
    int currentIndex = 0,
    Color backgroundColor = _kDefaultTabBarBackgroundColor,
    Color activeColor = CupertinoColors.activeBlue,
    Color inactiveColor = CupertinoColors.inactiveGray,
    double iconSize = 30.0,
  ) : assert(items != null),
      super(items: items, onTap: onTap, currentIndex: currentIndex, 
        backgroundColor: backgroundColor, activeColor: activeColor, 
        inactiveColor: inactiveColor, iconSize: iconSize);

  @override
  Widget build(BuildContext context) {
    //build logic for the custom bar
  }

  @override
  CustomTabBar copyWith({
    Key key,
    List<BottomNavigationBarItem> items,
    Color backgroundColor,
    Color activeColor,
    Color inactiveColor,
    Size iconSize,
    Border border,
    int currentIndex,
    ValueChanged<int> onTap,
  }) {
    return CustomTabBar(
      key: key ?? this.key,
      items: items ?? this.items,
      backgroundColor: backgroundColor ?? this.backgroundColor,
      activeColor: activeColor ?? this.activeColor,
      inactiveColor: inactiveColor ?? this.inactiveColor,
      iconSize: iconSize ?? this.iconSize,
      border: border ?? this.border,
      currentIndex: currentIndex ?? this.currentIndex,
      onTap: onTap ?? this.onTap
    );
  }
}

答案 1 :(得分:0)

通常,Flutter倾向于组合而不是继承。您想通过这种继承来完成什么工作?