I use this pattern for changing tabbar length with my items
class MyWidget extends StatefulWidget {
const MyWidget({Key? key}) : super(key: key);
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget>
with SingleTickerProviderStateMixin {
bool inited = false;
TabController? tabcontroller;
final List<OrderTabbarWidget> tabbarWidgets = [];
_initTabbarWidgets() async {
setState(() {
inited = false;
});
await Future.delayed(const Duration(
milliseconds: 100)); //some time i give error if this method not exists
final List<OrderTabbarWidget> _widgest = [];
int getIndex() => _widgest.length;
if (condition1)
_widgest.add(OrderTabbarWidget(NewOrderAddressPage(), getIndex(),
const Icon(Icons.location_on), OrderTabType.address));
_widgest.add(OrderTabbarWidget(const NewOrderItemsView(), getIndex(),
const Icon(Icons.category), OrderTabType.items));
if (condition2)
_widgest.add(OrderTabbarWidget(
const SubmitOrderDiscountPage(),
getIndex(),
const Icon(CustomIcons.discount_tag_svgrepo_com),
OrderTabType.discount));
if (condition3)
_widgest.add(OrderTabbarWidget(NewOrderDefaultShipping(), getIndex(),
const Icon(Icons.local_shipping), OrderTabType.shipping));
_widgest.add(OrderTabbarWidget(const NewOrderSubmitPage(), getIndex(),
const Icon(Icons.checklist_rtl_outlined), OrderTabType.submit));
_widgest.add(OrderTabbarWidget(const NewOrderPaymentPage(), getIndex(),
const Icon(Icons.payment), OrderTabType.payment));
tabbarWidgets
..clear()
..addAll(_widgest);
tabcontroller?.dispose();
tabcontroller = null;
tabcontroller =
new TabController(length: tabbarWidgets.length, vsync: this);
setState(() {
inited = true;
});
}
@override
void initState() {
_resetMyTabbar();
super.initState();
}
_resetMyTabbar() {
/** fetch items or anything need for tabbar **/
_initTabbarWidgets();
}
@override
Widget build(BuildContext context) {
if (!inited) return const NormalProgress();
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: _resetMyTabbar,
child: const Icon(Icons.refresh),
),
appBar: AppBar(
bottom: TabBar(
controller: tabcontroller,
tabs: List.generate(
tabbarWidgets.length, (index) => tabbarWidgets[index].tab)),
),
body: TabBarView(
controller: tabcontroller,
children: List.generate(
tabbarWidgets.length, (index) => tabbarWidgets[index].widget)),
);
}
}
OrderTabbarWidget
class OrderTabbarWidget {
final Widget widget;
final int index;
final Widget tab;
final OrderTabType type;
bool get isShipping => type == OrderTabType.shipping;
OrderTabbarWidget(this.widget, this.index, this.tab, this.type);
}