1

Suppose I have a function called callService() which return the responded data from a server. Now I want this function to be called after every 60s periodically.

Mohammad Sohail
  • 246
  • 5
  • 13
  • 3
    Does this answer your question? [flutter run function every x amount of seconds](https://stackoverflow.com/questions/52569602/flutter-run-function-every-x-amount-of-seconds) –  Dec 08 '20 at 06:32

2 Answers2

2

Use Timer

For More: Timer Class

Sample app output:

enter image description here

Here is the working Example:

import 'package:flutter/material.dart';
import "dart:async";

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int sec = 0;
  Timer timer;

  void _incrementCounter() {
// Timer.periodic will execute the code which is in the callback,
// in this case, we are increasing the sec state every second, 
// As you want to execute it every minute, put Duration(seconds: 60)

    Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        sec++;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Press to start timer',
            ),
            Text(
              '$sec',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
Ketan Ramteke
  • 10,183
  • 2
  • 21
  • 41
0

for this, just make a function for method call in init state,using Timer

 import 'dart:async';


Timer timer;

 @override
  void initState() {
    callMehtod();
  }


  Future<void> callMehtod() async {
    timer.periodic(Duration(seconds: 60), (timer) {
     //place you code for calling after,every 60 seconds.
    });
  }

@override
void dispose() {
  timer?.cancel();
  super.dispose();
}
Shirsh Shukla
  • 5,491
  • 3
  • 31
  • 44