【问题标题】:How to avoid re-fetching user info from Firebase with Flutter如何避免使用 Flutter 从 Firebase 重新获取用户信息
【发布时间】:2021-03-28 15:32:22
【问题描述】:

只要用户登录我的应用程序,就会将用户重定向到 homepage 并且 homepage 有一个 bottomNavigationBar 和一个 AppBar

在这个AppBar 中,我显示了用户的头像appname。为了展示这一点,我使用:

Stack(
            children: [
              FutureBuilder(
                future: getAvatar(),
                builder: (context, snapshot) {
                  if (snapshot.hasError) {
                    return ClipRRect(
                      borderRadius: BorderRadius.circular(25.0),
                      child: Image.asset(
                        'assets/default_avatar.png',
                        fit: BoxFit.cover,
                      ),
                    );
                  }

                  if (snapshot.connectionState == ConnectionState.done) {
                    return Center(
                      child: SizedBox(
                        height: 45.0,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(25.0),
                          child: FadeInImage.assetNetwork(
                            placeholder: 'assets/default_avatar.png',
                            image: snapshot.data['avatar'],
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                    );
                  }

                  return Scaffold(
                    body: Center(
                      child: CircularProgressIndicator(),
                    ),
                  );
                },
              ),
            ],

效果很好,但我认为这不是一个好习惯......每次我从底部导航栏更改页面时,头像都会“重新加载”(你会看到CircularProgressIndicator)。没有帮助它是一个有状态的类

因此,我阻止这种情况发生的解决方案是将用户数据保存在手机上的某个位置,并在需要时获取该信息。 但如何

仅供参考,不仅仅是头像,我会显示用户名和用户邮箱。如果有人有可以将我重定向到的示例,那就太好了!

谢谢!

【问题讨论】:

  • 使用颤振在本地存储数据已经发布:stackoverflow.com/a/41448527/8382028 Shared Preferences 可能是要走的路
  • 可以分享这门课的完整代码吗?
  • 为什么不使用 StreamBuilder 而不是 FutureBuilder?
  • @Lee3 菜鸟问题!
  • @Ants ????去过那里的兄弟!编码愉快!

标签: firebase flutter


【解决方案1】:

您错误地使用了FutureBuilder

docs 状态

未来一定是更早获得的,例如在 State.initState、State.didUpdateWidget 或 State.didChangeDependencies 期间。在构造 FutureBuilder 时,不能在 State.build 或 StatelessWidget.build 方法调用期间创建它。如果 Future 与 FutureBuilder 是同时创建的,那么每次 FutureBuilder 的 parent 重建时,异步任务都会重新启动。

您显然没有在此处执行此操作,因为您在build 期间获得了Future,因此预计任何时候调用build 您都会看到加载指示器。

initState 中获取Future 并将Future 传递给您的FutureBuilder

但是,如果您还使用PageView 或等效名称来管理您的页面,您还需要使用AutomaticKeepAliveClientMixin 并致电super.build(context)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2019-06-27
    • 2021-08-17
    • 2020-12-12
    • 1970-01-01
    相关资源
    最近更新 更多