如何仅在单击选项卡时才查询数据?

How to Query for data only when a tab is click in flutter?

我想创建一个类似于 Reddit 的标签栏,应用仅在我点击标签时加载数据,即政治。

如何使用选项卡栏和 TabBarView,以便在我单击它时仅从 firestore 加载数据,类似于 Reddit?

我的代码如下图:

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 ?
                  }),
                )
            ))
    ;
  }
}

使用flutter api TabBar link.

上面link中的示例对于创建TabBarView非常清楚。 如果您对此答案有任何问题评论,我会尽力帮助您。

TabBar小部件有一个名为onTap的参数,当用户点击一个Tab时会被触发,这个参数是一个带有输入参数的函数,它表示标签的索引,你可以根据这个索引号加载你的数据,例如:

appBar: AppBar(
  title: ...,
  bottom: TabBar(
    onTap: (selectedIndex) {
      switch(selectedIndex) {
        case 0: {
          /// ... load your data here
        }
        break;
        case 1: {
          /// ... load your data here
        }
        ...
      }
    },
    tabs: [],
  ),
),
  • 滑动标签时不会调用onTap事件,如果你想在用户在屏幕之间滑动时处理加载数据,你可以为你的标签添加一个控制器,here is an example
  • 如果加载数据是 time-consuming,最好使用某种异步加载方法,例如使用 BLOC 库,如果您不熟悉 BLOC 和状态管理主题,可以在 this link