flutter - 等到 firestore 中的数据成功更新

标签 flutter dart google-cloud-firestore

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

这是我更新文档的代码。

  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),
                  ],
                ),
              ),

最佳答案

要检查您的数据是否已成功更新,您需要捕获任何发生的错误。我已在此处修改了您的 updateTechnical() 函数:

  Future updateTechnical(Technical technical) async {
    return await technicalsCollection.doc(technical.id).update({
      "name": technical.name,
      "address": technical.address,
      "phoneNum": technical.phoneNum,
      "tools": technical.tools,
    }).then((value) => print("Updated successfully")) // success toast here
          .catchError((error) => print("Failed to update: $error")); // fail toast here
  }

您也可以使用 try/catch block ,但被认为效率较低,通常应尽可能避免使用

关于flutter - 等到 firestore 中的数据成功更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69176464/

相关文章:

firebase - 是否可以在 Flutter 中使用 FCM 实现通知分组/捆绑?

android - 使用底部导航栏在 Web View 中导航

firebase - Cloud Firestore 数据是否跨洲复制?

javascript - 如何将 Angular 中的日期作为时间戳保存到 Firestore?

Flutter 包读取自己的 Assets

image - 如何在Flutter中将图像下载到画廊

flutter - 在此ModalBottomSheet小部件上方找不到正确的Provider <X>

dart - 为什么 Dart 不允许 mixin 继承?

build - Dartium 使用 ffmpeg 在 Windows 上构建

firebase - #flutter:配置 ':cloud_firestore_web'时出现问题