首页 > 解决方案 > 等到firestore中的数据成功更新

问题描述

当用户单击保存按钮并显示 toast 或要求用户在文档未更新时再试一次时,我想检查数据是否已成功上传到 firestore。

这是我更新文档的代码。

  Future updateTechnical(Technical technical) async {
    return await technicalsCollection.doc(technical.id).update({
      "name": technical.name,
      "address": technical.address,
      "phoneNum": technical.phoneNum,
      "tools": technical.tools,
    });
  }

这是保存按钮

       ElevatedButton(
                onPressed: () {
                  DatabaseService().updateTechnical(
                    Technical(
                      id: selectedTechnical.id,
                      name: nameController.text,
                      address: addressController.text,
                      phoneNum: phoneController.text,
                      tools: selected.join(','),
                      
                    ),
                  );
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('Save  '),
                    Icon(Icons.person_add),
                  ],
                ),
              ),

标签: flutterdartgoogle-cloud-firestore

解决方案


等到数据成功更新,您可以使用.then().

onPressed: () {
   DatabaseService().updateTechnical().then((value) => {
                         print("successfully uploaded!"),
                    });
},

检查上传过程中是否发生任何错误,您应该检查updateTechnical()

 Future updateTechnical(Technical technical) async {
    try {
      final querySnapshot =
          await technicalsCollection.doc(technical.id).update({
        "name": technical.name,
        "address": technical.address,
        "phoneNum": technical.phoneNum,
        "tools": technical.tools,
      });
      return querySnapshot;
    } catch (error) {
      print(error); //here you can see the error messages from firebase
      throw 'failed';
    }
  }

如果您需要做某些事情,当发生特定错误时,不幸的是,您必须检查所有错误消息。这是一个示例:处理异常


推荐阅读