欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > flutter入门系列教程<三>:tabbar的高度自适用,支持无限滚动

flutter入门系列教程<三>:tabbar的高度自适用,支持无限滚动

2025/10/7 23:04:28 来源:https://blog.csdn.net/yan1915766026/article/details/145340913  浏览:    关键词:flutter入门系列教程<三>:tabbar的高度自适用,支持无限滚动

背景

在之前的文章中,简介了tabbar组件的使用,它通常用于顶部放置tabbar标签页头,内容全部都是TabbarView的全部内容,且内容通常是占满屏幕的(尽可能大),如下:
在这里插入图片描述

但是有时候我们需要在文章的中间部分使用tabbar,之前也简介了封装的方法,当时的思路是给tabbarView限制高度、或者使用expand组件包裹,但这样也不是很灵活。

因为,如果tabbarView下面还有其他组件,那么tabbarView的高度就被限制死了。

那么,能否实现tabbarView无论在哪里,上面下面是否有组件时,其高度都能自适用呢?

自定义tabbar

由于tabbarView组件的特性使然,它必须有固定的高度、或者声明为占据尽可能大的高度,所以如果要让tabbar高度自适用,那就得自己封装,即:不使用tabbarView组件,效果图如下:
请添加图片描述

自定义tabbar源码

以下仅为示例代码,但足可以应付开发中的大部分需求,仅供参考:

import 'package:flutter/material.dart';class CustomTabBarExample extends StatefulWidget {const CustomTabBarExample({super.key});State<CustomTabBarExample> createState() => _CustomTabBarExampleState();
}class _CustomTabBarExampleState extends State<CustomTabBarExample> {int _selectedTabIndex = 0;Widget build(BuildContext context) {return DefaultTabController(length: 3, // Tab 的数量child: Scaffold(appBar: AppBar(title: const Text('自适用的tabbar'),),body: SingleChildScrollView(child: Column(children: [// 顶部部分,可自定义内容Container(height: 100,color: Colors.blue,child: const Center(child: Text('Top Section'),),),// TabBarTabBar(onTap: (index) {setState(() {_selectedTabIndex = index;});},tabs: const [Tab(text: 'Tab 1'),Tab(text: 'Tab 2'),Tab(text: 'Tab 3'),],),// 根据选中的 Tab 索引显示不同的内容_buildTabContent(_selectedTabIndex),// 底部部分,可自定义内容Container(height: 100,color: Colors.orange,child: const Center(child: Text('Bottom Section'),),),],),),),);}Widget _buildTabContent(int index) {switch (index) {case 0:return Container(height: 70,color: Colors.red,child: const Center(child: Text('Tab 1 Content'),),);case 1:return Container(height: 800,color: Colors.green,child: const Center(child: Text('Tab 2 Content'),),);case 2:return Container(height: 150,color: Colors.yellow,child: const Center(child: Text('Tab 3 Content'),),);default:return Container();}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词