Flutter:让BottomNavigationBar保持状态

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

@有问题。
如果有关注过我的同学可能看过我之前的一篇名为Flutter学习笔记:BottomNavigationBar实现多个Navigation的文章,这篇文章主要是介绍了通过Navigation实现保持住让BottomNavigationBar页面的状态,从而避免在BottomNavigationBar切换时导致页面重新initState。但这么做有一个严重的问题,就是当我们在对应页面执行Navigator.push()时,也就是跳转页面时,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切换的时候就不会丢失状态了,怎么样你的问题解决了吗?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容