Flutter 去除TabBarView 左右滑动的动画效果

是这样的,前面我提到使用 Flutter TabBar + TabBarView 实现顶部导航栏,但这样的导航页面有左右滑入滑出的动画效果,很明显也很难看,想着去掉。不是禁止左右滑动,而是点击下方导航栏 Tab 切换时,不要 TabBarView 的左右切换动画。下面是修改后的效果,点击后直接显示,没有侧滑显示的效果。

禁止滑动

如果想禁止左右滑动,那直接设置 physics 就行了,但这不是我文章要分享的。

TabBarView(
  controller: _tabController,
  physics: NeverScrollableScrollPhysics(), // 禁用滑动
  children: [
    // ...页面
  ],
)

去除滑动动画

我们不是要禁止,而是要无动画的页面切换。这需要用 IndexedStack 代替 TabBarView,它可以显示其子组件列表中的一个,而不带有任何动画效果。然后我们监听 TabController 的变化切换 IndexedStack 的索引就行了。

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    _tabController.addListener(() {
      setState(() {}); // 当选中的选项卡更改时,更新界面
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack( // TabBarView 替换为 IndexedStack
        index: _tabController.index, // 当标签控制器的变化,更新 index
        children: [
          ...
        ],
      ),
      bottomNavigationBar: Container(
        height: 64.h,
        decoration: ShadowStyle.white12TopSpread4Blur10(radius: 0),
        child: Material(
          color: Theme.of(context).inputFillColor,
          child: TabBar(
            controller: _tabController,
            indicator: const BoxDecoration(),
            labelColor: Theme.of(context).tabLabelColor,
            unselectedLabelColor: Theme.of(context).tabUnselectedLabelColor,
            labelStyle: TextStyle(fontSize: 12.sp,),
            unselectedLabelStyle: TextStyle(fontSize: 12.sp),
            tabs: [
              ...
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

}

以上注释就是要修改的代码。

本文由老郭种树原创,转载请注明:https://guozh.net/remove-the-animation-effect-of-tabbarview-sliding/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注