Flutter:让BottomNavigationBar保持状态

版本所有,转载请注明出处

@有问题。
如果有关注过我的同学可能看过我之前的一篇名为Flutter学习笔记:BottomNavigationBar实现多个Navigation的文章,这篇文章主要是介绍了通过Navigation实现保持住让BottomNavigationBar页面的状态,从而避免在BottomNavigationBar切换时导致页面重新initState。但这么做有一个严重的问题,就是当我们在对应页面执行Navigator.push()时,也就是跳转页面时,BottomNavigationBar 始终保持在页面底部,如下图:

Flutter:让BottomNavigationBar保持状态
image.png

显然这不是我们想要的结果。经过努力,我偶然发现了一个解决方法,以官方的Gallery为例:

    return new FadeTransition(
      opacity: _animation,
      child: new SlideTransition(
        position: new Tween<Offset>(
          begin: const Offset(0.0, 0.02), // Slightly down.
          end: Offset.zero,
        ).animate(_animation),
        child: new IconTheme(
          data: new IconThemeData(
            color: iconColor,
            size: 120.0,
          ),
          child: new Semantics(
            label: 'Placeholder for $_title tab',
            child: _buildChild(),
          ),
        ),
      ),
    );

这是官方的原代码,要想让页面保持住状态仅需要添加一个Key:

    return new FadeTransition(
      key: ObjectKey("$_title"),
      opacity: _animation,
      child: new SlideTransition(
        position: new Tween<Offset>(
          begin: const Offset(0.0, 0.02), // Slightly down.
          end: Offset.zero,
        ).animate(_animation),
        child: new IconTheme(
          data: new IconThemeData(
            color: iconColor,
            size: 120.0,
          ),
          child: new Semantics(
            label: 'Placeholder for $_title tab',
            child: _buildChild(),
          ),
        ),
      ),
    );

这样每次BottomNavigationBar切换的时候就不会丢失状态了,怎么样你的问题解决了吗?