如何设置计时器以在Flutter中定期更新API数据

问题描述 投票:0回答:1

我正在从API获取数据并将其加载到列表视图。我的列表视图显示查询结果没有任何问题。我想通过定期从API获取数据来更新列表视图。最好的方法是什么?

这是我在主屏幕的initState中调用API方法的方式。

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    _fixtureData = getFixture();
  }

  Future<List<Fixtures>> getFixture() async {
    fixtureList = await FootballApi.getFixtureData();
    return fixtureList;
  }

这是我通过主屏幕上的FutureBuilder呈现ListView的代码。

              FutureBuilder<List<Fixtures>>(
                  future: _fixtureData,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      fixtureList = snapshot.data;

                      return AppListView(
                        matchList: fixtureList,
                        //callback function brings the matchCounter value from ListView class
                        onChange: (value) {
                          setState(() {
                            matchCounter = value;
                          });
                        },
                        finalBetList: (value) {
                          setState(() {
                            betList = value;
                          });
                        },
                      );
                    }
                    return Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        SizedBox(
                          child: CircularProgressIndicator(),
                          width: 60,
                          height: 60,
                        ),
                        const Padding(
                          padding: EdgeInsets.only(top: 16),
                          child: Text(
                            'Awaiting result...',
                            style: TextStyle(color: Colors.white),
                          ),
                        )
                      ],
                    );
                  },
                ),

这是我调用的API方法。

static Future<List<Fixtures>> getFixtureData() async {
    Map<String, String> queryParameters = {
      'league': '79',
      'next': '5',
    };


    http.Response response = await http.get(
      getUrl('fixtures', queryParameters),
      headers: requestHeaders,
    );

    if (response.statusCode == 200) {
      String data = response.body;
      List<dynamic> result = jsonDecode(data)['response'];

      for (int i = 0; i < result.length; i++) {
        Fixtures fixture = Fixtures();

        fixture.leagueID = jsonDecode(data)['response'][i]['league']['id'];
        fixture.country = jsonDecode(data)['response'][i]['league']['country'];
        fixture.leagueName = jsonDecode(data)['response'][i]['league']['name'];
        fixture.fixtureID = jsonDecode(data)['response'][i]['fixture']['id'];

        //get Odds to match with fixtures by fixtureID
        await getOddsData(fixture.fixtureID);

        fixture.dateTime =
            DateTime.parse(jsonDecode(data)['response'][i]['fixture']['date']);
        fixture.homeTeam =
            jsonDecode(data)['response'][i]['teams']['home']['name'];
        fixture.awayTeam =
            jsonDecode(data)['response'][i]['teams']['away']['name'];
        fixture.status =
            jsonDecode(data)['response'][i]['fixture']['status']['long'];
        fixture.homeGoals = jsonDecode(data)['response'][i]['goals']['home'];
        fixture.awayGoals = jsonDecode(data)['response'][i]['goals']['away'];
        fixture.htScoreHome =
            jsonDecode(data)['response'][i]['score']['halftime']['home'];
        fixture.htScoreAway =
            jsonDecode(data)['response'][i]['score']['halftime']['away'];
        fixture.ftScoreHome =
            jsonDecode(data)['response'][i]['score']['fulltime']['home'];
        fixture.ftScoreAway =
            jsonDecode(data)['response'][i]['score']['fulltime']['away'];

        if (oddsList.length > 0) {
          for (int j = 0; j < oddsList.length; j++) {
            if (oddsList[j].fixtureID == fixture.fixtureID) {
              fixture.homeOdds = oddsList[j].homeOdds;
              fixture.drawOdds = oddsList[j].drawOdds;
              fixture.awayOdds = oddsList[j].awayOdds;
              fixture.bookmakerName = oddsList[j].bookmakerName;
              FootballApi.fixtureList.add(
                  fixture);
            }
          }
        }
      }
    } else {
      print('statusCode: ' + response.statusCode.toString());
    }

    return FootballApi.fixtureList;
  }
api flutter dart timer future
1个回答
0
投票

计时器将是一个不错的选择。一旦您的状态被初始化,就启动一个计时器,并在小部件被处置后就开始处置。在计时器内部,调用API和小部件的setState

 @override
 void initState() {
   _timer = new Timer.periodic(Duration(seconds: 30), 
   (_) => getFixture());
   super.initState();
 }

 @override
 void dispose() {
   _timer.cancel();
   super.dispose();
 }
© www.soinside.com 2019 - 2024. All rights reserved.