首页 > 解决方案 > Flutter - 覆盖 CupertinoTabBar 的“构建”方法

问题描述

我目前正在尝试通过让我自己的类扩展它并覆盖“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。

标签: dartflutter

解决方案


您需要覆盖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
    );
  }
}

推荐阅读