【问题标题】:How to add the toggle switch button from flutter to firebase firestore database如何将切换开关按钮从颤振添加到 Firebase Firestore 数据库
【发布时间】:2019-10-12 16:55:30
【问题描述】:

我正在尝试设置一个从颤动到 Firestore 的切换开关按钮。我已经在我的flutter项目中设置了依赖项,但是我不知道如何将交换机与firestore连接。

我正在尝试制作一个可用于控制灯光的开/关开关;我已经尝试给它一些值,但即便如此,我也不确定如何与 firestore 连接。

class _HomeState extends State<Home> {

 bool _value = false;

  void _onChanged(bool value) {
   setState(() {
    _value = value; 
   });

  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home ${widget.user.email}'),
      ),
      body: new Container(
        padding: new EdgeInsets.all(32.0),
        child: new Column(
          children: <Widget>[
            new SwitchListTile.adaptive(
                title: new Text('Bedroom light'),
                activeColor: Colors.red,
                secondary: const Icon(Icons.lightbulb_outline),
                value: _value,
                onChanged: (bool value) {
                  _onChanged(value);

                })
          ],
        ),
      ),
    );
  }
}

这是我到目前为止的代码。我知道我们必须使用 StreamBuilder,但我想知道如何使用。

【问题讨论】:

  • 你检查过firestore包上的例子吗?pub.dev/packages/cloud_firestore
  • 是的,我确实检查了 firestore 包,但是,我不知道如果我关掉灯,它也会在 firestore 中改变。

标签: firebase flutter google-cloud-firestore


【解决方案1】:

你必须先在firestore中创建一个数据库引用-

databaseReference = Firestore.instance.collection('Switches').where('switch','==',/*ANY NAME*/);

然后运行一个转换来更新value的值

Firestore.instance.runTransaction((transaction) async {
    await transaction.update(
    documentReference, _value);
};

只需确保在 Firestore 中,将采用 _value 值的字段是boolean

【讨论】:

    猜你喜欢
    • 2019-01-19
    • 2019-02-25
    • 2021-01-31
    • 2021-09-04
    • 2018-11-06
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2019-02-17
    相关资源
    最近更新 更多