繁体   English   中英

Flutter:带有 FutureBuilder 或 StreamBuilder 的 TabBar

[英]Flutter: TabBar with FutureBuilder or StreamBuilder

我有一个TabBar可以与FutureBuilder一起工作。 这只执行一次,当我在选项卡之间切换时,它不需要再次加载。 当我对此选项卡内的元素进行一些更改时,我会重新加载它。 直到这里一切都好。

问题是这会造成一些复杂性,因为我现在必须对内部元素进行越来越多的更新。

因此,使用StreamBuilder解决问题,但在切换选项卡时会再次触发。 首先,用户体验不是每次都显示加载器那么好,其次,这是从 Firebase 获取文件增加成本。

有没有更好的方法来显示 Firebase 文档中的标签?

class BottomBarState extends State<BottomBar>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {

@override
  bool get wantKeepAlive => true;

@override
  Widget build(BuildContext context) {
    super.build(context);

    return Container(
      child: tabs(),
    );
  }

return StreamBuilder<QuerySnapshot>(
      stream: FirebaseProfile().getPortfolios(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        if (!snapshot.hasData) return const Loader();
        if (snapshot.data == null) return const Loader();

        portfolios = snapshot.data!.docs;

        return scaffold(); // the rest of it it's not really important since this Stream should execute only the first time and when I perform changes in the DB
      },
    );
  }

您可以为每个页面使用 StateFulWidget 并在 state 添加AutomaticKeepAliveClientMixin ,这将使每个选项卡保持活动状态并防止重新加载。 希望有用

class Page extends StatefulWidget {
  Page({Key? key}) : super(key: key);

  @override
  State<Page> createState() => _PageState();
}

class _PageState extends State<Page> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    return Container();
  }

  @override
  bool get wantKeepAlive => true;
}

问题在于我声明 stream 的方式。 这个视频很好地解释了它:

https://youtu.be/sqE-J8YJnpg

所以改变会是这样的:

class BottomBarState extends State<BottomBar>
    with TickerProviderStateMixin {
  var portfoliosStream;

@override
  void initState() {
    super.initState();
    portfoliosStream = FirebaseProfile().getPortfolios();
  }

@override
  Widget build(BuildContext context) {
    super.build(context);

    return Container(
      child: tabs(),
    );
  }

return StreamBuilder<QuerySnapshot>(
      stream: portfoliosStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        if (!snapshot.hasData) return const Loader();
        if (snapshot.data == null) return const Loader();

        portfolios = snapshot.data!.docs;

        return scaffold(); // the rest of it it's not really important since this Stream should execute only the first time and when I perform changes in the DB
      },
    );
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM