Issue
I want to create a tab bar similar to Reddit's where the app only loads the data when I click on a tab, i.e. Politics.
How can I use the tab bar and TabBarView such that I only load the data from firestore when I click on it similar to Reddit?
My code is as shown below:
class TabsDemo extends StatefulWidget {
@override
_TabsDemoState createState() => _TabsDemoState();
}
class _TabsDemoState extends State<TabsDemo> {
TabController _controller;
/// this list will change according to what they prefer their interested category to be
List<String> categories = ["All", "Politics", "USA", "World"];
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext ctxt) {
return DefaultTabController(
length: categories.length,
child: new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.black,
bottom: new TabBar(
labelColor: Colors.white70,
unselectedLabelColor: Colors.white30,
labelPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 3),
indicator: BoxDecoration(
borderRadius: BorderRadius.circular(27),
color: Colors.transparent),
isScrollable: true,
tabs: List<Widget>.generate(categories.length, (int index) {
print(categories[0]);
return Padding(
padding: const EdgeInsets.only(left: 9.0, right:9),
child: new Tab(
text: categories[index]),
);
}),
),
),
body: new TabBarView(
children: List<Widget>.generate(
categories.length, (int index) {
/// how should I fill this ?
}),
)
))
;
}
}
Solution
The TabBar
widget has a parameter named onTap
which will be triggered when user taps on a Tab, this parameter is a function with an input parameter which indicates the index of tab, you can load your data based on this index number, for example:
appBar: AppBar(
title: ...,
bottom: TabBar(
onTap: (selectedIndex) {
switch(selectedIndex) {
case 0: {
/// ... load your data here
}
break;
case 1: {
/// ... load your data here
}
...
}
},
tabs: [],
),
),
- onTap event get not called when you swipe tabs, if you want to handle loading data when user swipes between screens, you can add a controller for you tabs, here is an example
- If loading data is time-consuming, it's better to use some kind of Async loading approaches like using BLOC library, if you're not familiar with BLOC and State Management topic, you can take a loot at this link
Answered By - Mahmoud_Mehri
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.