Flutter 仿掘金之动态Tabbar

本文介绍了如何在Flutter中创建动态Tabbar,通过结合TabBarView、DefaultTabController和TabController实现。强调了TabController在接收帧刷新通知中的作用,并提供了一种使用本地缓存动态创建Tabbar的方法。同时提醒在实现过程中需要注意TabController的重新创建和Tabbar在AppBar的位置设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果

不多逼逼

Tabbar

先看Tabbar的参数

const TabBar({
    Key key,
    @required this.tabs, // item
    this.controller, //控制器
    this.isScrollable = false, //是否可以滑动
    this.indicatorColor, //指示器的颜色
    this.indicatorWeight = 2.0,
    this.indicatorPadding = EdgeInsets.zero,
    this.indicator,//自定义指示器
    this.indicatorSize,
    this.labelColor, // 选中文字颜色
    this.labelStyle, // 
    this.labelPadding, // 文字的内边距
    this.unselectedLabelColor, // 未选中文字颜色
    this.unselectedLabelStyle,
    this.dragStartBehavior = DragStartBehavior.start, 
    this.onTap,// 点击事件
  })

TabBarView

 const TabBarView({
    Key key,
    @required this.children, // 每页的view
    this.controller, // 控制器
    this.physics,
    this.dragStartBehavior = DragStartBehavior.start,
  })

好了,这两个必须关联起来用. 不然会报错

DefaultTabController

这个是一个无状态的控制器,很简单.但是要做成动态Tabbar的话,不能用这个.

TabController

也很简单.

 TabController({ int initialIndex = 0, @required this.length, @required TickerProvide
Flutter 中的动态TabBar通常是指在应用中可以动态地切换和显示不同页面的Tab栏组件,它可以根据数据的变化实时更新展示的内容。在`MaterialApp`中,你可以通过` tabBar:`属性来设置自定义的`BottomNavigationBar`,并结合`List<Widget>`或者`StatefulWidget`来实现动态内容。 例如,你可以创建一个`TabBarView`包裹一组`Tab`,每个`Tab`代表一个页面,然后在对应的`State`中管理页面的数据和状态: ```dart class DynamicTabBar extends StatefulWidget { final List<String> titles; // 标题列表 final List<WidgetBuilder> pages; // 页面构建函数列表 const DynamicTabBar({Key? key, required this.titles, required this.pages}) : super(key: key); @override _DynamicTabBarState createState() => _DynamicTabBarState(); } class _DynamicTabBarState extends State<DynamicTabBar> { int _selectedIndex = 0; @override Widget build(BuildContext context) { return BottomNavigationBar( currentIndex: _selectedIndex, items: widget.titles.map((title, index) { return BottomNavigationBarItem( icon: Icon(Icons.navigate_next), label: title, onTap: () { setState(() { _selectedIndex = index; }); }, ); }).toList(), onTap: (index) { setState(() { _selectedIndex = index; }); }, type: BottomNavigationBarType.fixed, // 或者BottomNavigationBarType.shifting unselectedItemColor: Colors.grey, // 默认颜色 selectedColor: Colors.blue, // 选中颜色 showUnselectedLabels: false, // 是否显示未选中标签 ); // 当前显示的页面 return TabBarView( children: widget.pages.map((pageBuilder) { return pageBuilder(context, index: _selectedIndex); }).toList(), ); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值