Firebase 列表未在设置状态下更新

标签 firebase flutter google-cloud-firestore

从 Firebase 检索后,Flutter setState 函数未更新列表。

我正在尝试开发一个 Flutter 应用程序。我没有更新 setState() 函数中的列表。该列表已成功从 firebase 检索。我已在 Services.dart 文件中编写了 firebase 连接。

但是我的方法 _getList() 没有获取 main.dart 文件中的值。

ma​​in.dart

    class DetailsPageState extends State<DetailsPage> {

    List<Product> list;

        @override
    void initState() {
        _checkUser();  // for getting user id from firebase auth
    }

        @override
    Widget build(BuildContext context) {
            return new Scaffold(
                body: new Container(
                    child:new Text("data");
                );
            )
    }

    void _checkUser(){
        debugPrint("Entering in _checkUser");
        this.firebaseAuth.onAuthStateChanged.listen((firebaseUser)async{
            _getList(firebaseUser.uid);
        });
    }


    void _getList(String id)
    debugPrint("Entering in _getList");
        Services.retrieveItems(firestore, uid).then((onValue){
                setState(() {
                    list=onValue;
                        debugPrint("items list:"+onValue.length.toString());
                        debugPrint("items list:"+listCart.length.toString());
                });
        });
        }
    }

Services.dart

    static Future<List> retrieveItems(Firestore firestore, String userId) async {
        List<Product> items = new List<Product>();
        try {
        firestore.collection("Items").document(userId)
        .collection("ItemsMain").snapshots().listen((QuerySnapshot snapshot)  {
            List docList = snapshot.documents;
            items = snapshot.documents.map((documentSnapshot) => Product.fromMap(documentSnapshot.data)).toList();
            debugPrint("items:"+items.length.toString());
            //return items;
        });
        } on Exception catch (e) {
        print (e.toString());
        }

        debugPrint("items 2:"+items.length.toString());
        return items;
    }

预期结果:

输入_checkUser

进入_getList

项目:6

项目 2:6

项目列表:6

项目列表:6

实际结果:

输入_checkUser

进入_getList

项目列表:0

项目列表:0

项目 2:0

项目:6

最佳答案

您将在元素装载之前将其退回。解决此问题的最简单方法是在 retrieveItems 中使用 await 来等待从 Firestore 加载数据:

static Future<List> retrieveItems(Firestore firestore, String userId) async {
    List<Product> items = new List<Product>();
    var snapshot = await firestore.collection("Items").document(userId)
                                  .collection("ItemsMain").getDocuments()
    List docList = snapshot.documents;
    items = snapshot.documents.map((documentSnapshot) => Product.fromMap(documentSnapshot.data)).toList();
    debugPrint("items:"+items.length.toString());

    return items;
}

你会注意到我:

  • 调用get()而不是listen()。由于 listen() 开始主动监视集合,因此无法判断它何时“完成”。另一方面,get() 返回文档一次,然后完成。
  • 删除了异常处理,只是为了使代码更具可读性。但我也建议仅在您实际处理异常时才在这样的功能代码中添加异常处理程序。将“记录并继续”处理程序留给更高级别的代码,例如您的 main 方法。

关于Firebase 列表未在设置状态下更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53867404/

相关文章:

firebase - 没有为 '[]' 类型定义运算符 'Object'

caching - 如何在 Firebase 托管中利用浏览器缓存

ios - 使用 Firebase Auth 时应用崩溃,原因 : 'Default app has already been configured.'

firebase - StreamBuilder 中的 Where 子句 Google Cloud Firestore

macos - 错误 : Unable to 'pub upgrade' flutter tool. 五秒后重试...(还剩 9 次尝试)

android - flutter :将所有小部件排列成行

android - 关于 Firestore 中查询的随机结果

firebase - 从 Cloud Functions for Firebase 调用 Google AppS 脚本 Web App

android - In-App billing 连接到 Firebase 并获取 Products

android - 如何检查按钮是否被按下