0

I am trying to push data to firebase using flutter. I know how to push data to firebase using the add function with the collection name.

I have the speed using the speedometer api , and I want to push the data to firebase every 5s.

please help me to send data without using a button.

  • 1
    Welcome. Please add some code to show us what you have tried so far. https://stackoverflow.com/help/how-to-ask – James Feb 12 '21 at 22:07

1 Answers1

0

You need to write a code that runs every 5 seconds, using this answer https://stackoverflow.com/a/15298728/8572736 together with a statefull widget I was able to come up with this.

in your statefull widget in the initstate add this

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

this will keep calling PushSpeedToDB every 5 seconds then in your pushSpeedToDB

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

In the push speed to db, you can get the speed from the api and add it to your cloud firestore document.

This is how the complete code looks like

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();
  }



}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Musa Jahun
  • 66
  • 1
  • 6