如何将定时器添加到 changenotifier class

how to add timer to the changenotifier class

我正在使用 flutter 提供程序包来获取数据。

我有 2 个问题。

  1. 在 DataProvider class 中,我确实初始化了它 运行 3 次以 获取数据,
  2. 我需要每 5 分钟更新一次数据(我正在更新 通过调用 api) 的数据我怎么能执行它,我认为需要 添加计时器 fuction.where 我可以添加那些吗?

`

class DataProvider with ChangeNotifier {

      DataProvider() {
        getData();
 /*this will call 3 times when i call changenotifier provider in the ui*/
      }
    
      List<Data> _vData = [];
    //<Data> is my mode
      List<Data> get vData => _vData ;
    
       getData() async {
        try {
          _vData = await instatntApi().Services();
    // got the data from service
          notifyListeners();
          return _vData ;
        } catch (e) {
          print("error provider $e");
        }
      }
    }

`

这是我的 ui 电话

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

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

class _HomePageState extends State<HomePage> {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: ChangeNotifierProvider<DataProvider>(
            create:
                (context) => DataProvider(),
            child:  Builder(
              builder: (
                context,
              ) {
                final model = Provider.of<DataProvider>(context);

                return ListView.builder(
                    itemCount: model.vData.length,
                    itemBuilder: (BuildContext context, int index) {
                      
                      return Center(
                        child: Text(
                          model.vData[index].text.toString(),
                          style: TextStyle(color: Colors.black),
                        ),
                      );
                    });
              },
            ),
          ),
        ),
      ),
    );
  }
}

你可以试试Timer.periodic

class DataProvider with ChangeNotifier {
   bool _call = false;
      DataProvider() {
        if(!_call){
           getData();
           _call = true;
        }
      }
    
      List<Data> _vData = [];
    
      List<Data> get vData => _vData ;
    
       getData() async {
        await processData();
         Timer.periodic(Duration(minute: 5), (t){
           processData();
         });
      }

      processData() async{
       try {
          _vData = await instatntApi().Services();
    // got the data from service
          notifyListeners();
        } catch (e) {
          print("error provider $e");
        }
      }
    }