firebase - 根据按钮状态向 FireStore 发送 bool 值

标签 firebase flutter google-cloud-firestore

我使用 flutter 和 ESP32 创建了一个简单的家庭自动化项目,在我的应用程序上,我有一堆按钮,如果按下或不按下,它们将更改 firestore 内变量的状态。如果按下则发送 True,否则发送 false。我正在努力实现这一目标,但似乎做不到。

在 onPressed 内部是我尝试过的,所有代码都在 Stateful 类中:

bool pressed = false;

Random no effect code...

CustomButton(
        icon: Icons.lightbulb_outline,
        text: 'On',
        text2: 'Lâmpada 1\nSchuma',
        onPressed: () => (){
             dynamic databaseReference = Firestore.instance.collection('sensores').where('Led1','==',pressed);
        Firestore.instance.runTransaction((transaction) async {
          await transaction.update(
        documentReference, _value);
        };
         },
        ),
        SizedBox(width: 30.0),

        CustomButton(
        icon: Icons.lightbulb_outline,
        text: 'On',
        text2: 'Lâmpada 2\nSchuma',
        onPressed: () => (){
        },

我的消防仓库: Image

第二次尝试:

CustomButton(
                        icon: Icons.lightbulb_outline,
                        text: 'On',
                        text2: 'Lâmpada 1\nSchuma',
                        onPressed: () => (){
                          Firestore.instance.collection("sensores").document("2KbeT....").updateData({
                          'Led1': true,
                        });
                        },
                      ),

问题出在按钮格式上。 Uni 发送的代码效果很好。

最佳答案

首先将 firebase 添加到您的应用中:https://firebase.google.com/docs/flutter/setup?platform=ios

(导入 Firestore)

您只需更新您的数据即可:

Firestore.instance.collection('YourCollection').document('YourDocument').updateData({
 'Led1': true,
});

从服务器获取数据:

await Firestore.instance
    .collection('YourCollection')
    .document('YourDocument')
    .get()
    .then((DocumentSnapshot ds) {
  led1 = ds["Led1"];
  led2 = ds["Led2"];
  led3 = ds["Led3"];
});

我建议使用 MQTT 协议(protocol)与 ESP32 进行通信,而不是将其存储在 firestore 中。请注意,firestore 允许您每天进行 20k 读取和 50k 写入,因此如果您的设备需要更多数据,则使用 firestore 作为通信方法是不切实际的。

关于firebase - 根据按钮状态向 FireStore 发送 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61584213/

相关文章:

html - 三个网页可以在 Firebase (Firebase Hosting) 的同一个元素中吗?

flutter - 如何在Firebase和Bloc中使用json和序列化?错误:将对象转换为可编码对象失败

swift - 使用自定义解码器解码 Firestore 结构时获取 DocumentID

google-cloud-firestore - Firestore 安全规则 - 通配集合名称?

node.js - Firebase -如何查找我正在使用的 Firebase SDK 版本和库

Xamarin 表单中的 Firebase 分析

javascript - 向特定设备发送通知

Flutter iOS Back Swipe 不会调用 onWillPop

android - 如何在不占用更多空间的情况下在末端抽屉中添加可滚动 ListView ?

firebase - 使用 flutter 在 Firestore 中创建链接到用户 ID 的集合