【问题标题】:push data to firebase , flutter将数据推送到firebase,颤动
【发布时间】:2021-02-12 21:05:34
【问题描述】:

我正在尝试使用颤振将数据推送到 Firebase。我知道如何使用带有集合名称的 add 函数将数据推送到 firebase。

我使用 speedometer api 获得了速度,我想每 5 秒将数据推送到 firebase。

请帮我在不使用按钮的情况下发送数据。

【问题讨论】:

标签: flutter firebase-realtime-database


【解决方案1】:

您需要编写一个每 5 秒运行一次的代码,使用这个答案 https://stackoverflow.com/a/15298728/8572736 以及我能够想出的一个有状态的小部件。

在 initstate 的 statefull 小部件中添加此

void initState() {
    future= new Future.delayed(const Duration(seconds: 5));
    subscription = future.asStream().listen(PushSpeedToDb());
    super.initState();
  }
  

这将继续每 5 秒调用一次 PushSpeedToDB 然后在你的 pushSpeedToDB 中

  void PushSpeedToDb() async {
    //await get speed from speed api
    //await add the currentSpeed  the the cloud firestore document
  }

在push speed to db中,你可以从api中获取速度并将其添加到你的cloud firestore文档中。

这就是完整代码的样子

class SpeedWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => SpeedWidgetState();
}

class SpeedWidgetState extends State<SpeedWidget> {
  var future;
  var subscription;
  @override
  void initState() {
    future= new Future.delayed(const Duration(seconds: 5));
    subscription = future.asStream().listen(PushSpeedToDb());
    super.initState();
  }
  void PushSpeedToDb() async {
    //await get speed from speed api
    //await add the currentSpeed  the the cloud firestore document
  }
  
  @override
  void dispose() {
    super.dispose();
    subscription?.cancel();
  }
  
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }



}

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2021-08-28
    相关资源
    最近更新 更多