Use the TabBar
widget with the BLoC (Business Logic Component) pattern in Flutter
The TabBar
widget in Flutter is a horizontal row of tabs that allow the user to navigate between different views or pages within an app. To use the TabBar
widget with the BLoC (Business Logic Component) pattern in Flutter, you'll need to do the following:
- Create a
TabController
: ATabController
is responsible for coordinating the state of theTabBar
and theTabBarView
. You'll need to create a singleTabController
and share it between theTabBar
and theTabBarView
. - Create a
TabBar
: TheTabBar
widget displays the tabs and allows the user to switch between them. You'll need to provide theTabController
to theTabBar
using thecontroller
property. You can also customize the appearance of theTabBar
using various properties such astabs
,indicatorColor
, andlabelColor
. - Create a
TabBarView
: TheTabBarView
widget displays the content of each tab. You'll need to provide theTabController
to theTabBarView
using thecontroller
property. You can also customize the appearance of theTabBarView
using various properties such aschildren
andphysics
.
Here’s an example of how you might use the TabBar
and TabBarView
widgets with the BLoC pattern in Flutter:
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(vsync: this, length: 2);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My App'),
bottom: TabBar(
controller: _tabController,
tabs: [
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
],
),
),
body: TabBarView(
controller: _tabController,
children: [
Text('Content of tab 1'),
Text('Content of tab 2'),
],
),
);
}
}
I hope this helps! Let me know if you have any questions.