在Flutter中以间隔自动获取Api数据 [英] Fetch Api Data Automatically with Interval in Flutter

查看:97
本文介绍了在Flutter中以间隔自动获取Api数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Flutter应用程序上,我试图显示更新数据.我成功地从weather api手动获取了数据.但是我需要每5秒不断获取数据.因此,它应该自动更新.这是我在Flutter中的代码:

On my flutter application I am trying to show updating data. I am successful in getting data from weather api manually. But I need to constantly grab data every 5 seconds. So it should be updated automatically. Here is my code in Flutter :

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sakarya Hava',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Sakarya Hava'),
        ),
        body: Center(
          child: FutureBuilder<SakaryaAir>(
            future: getSakaryaAir(), //sets the getSakaryaAir method as the expected Future
            builder: (context, snapshot) {
              if (snapshot.hasData) { //checks if the response returns valid data
                return Center(
                  child: Column(
                    children: <Widget>[
                      Text("${snapshot.data.temp}"), //displays the temperature
                      SizedBox(
                        height: 10.0,
                      ),
                      Text(" - ${snapshot.data.humidity}"), //displays the humidity
                    ],
                  ),
                );
              } else if (snapshot.hasError) { //checks if the response throws an error
                return Text("${snapshot.error}");
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }


  Future<SakaryaAir> getSakaryaAir() async {
    String url = 'http://api.openweathermap.org/data/2.5/weather?id=740352&APPID=6ccf09034c9f8b587c47133a646f0e8a';
    final response =
    await http.get(url, headers: {"Accept": "application/json"});


    if (response.statusCode == 200) {
      return SakaryaAir.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load post');
    }
  }
}

我发现这样的代码片段可以从中受益:

I found such a snippet to benefit from :

// runs every 5 second
Timer.periodic(new Duration(seconds: 5), (timer) {
   debugPrint(timer.tick);
});

可能我需要用此代码片段包装并调用FutureBuilder,但我不知道该怎么做.

Probably I need to wrap and call FutureBuilder with this snippet but I was not able to understand how to do it.

推荐答案

您可以重构FutureBuilder以使用Future变量,而不用在FutureBuilder中调用方法.这将要求您使用StatefulWidget,并且可以在initState中设置将来并通过调用setState对其进行更新.

You can refactor your FutureBuilder to use a Future variable instead of calling the method in the FutureBuilder. This would require you to use a StatefulWidget and you can set up the future in your initState and update it by calling setState.

因此,您有一个将来的变量字段,例如:

So you have a future variable field like:

Future< SakaryaAir> _future;

所以您的initState看起来像这样:

So your initState would look like this :

@override
  void initState() {
    super.initState();
    setUpTimedFetch();
  }

其中setUpTimedFetch定义为

  setUpTimedFetch() {
    Timer.periodic(Duration(milliseconds: 5000), (timer) {
      setState(() {
        _future = getSakaryaAir();
      });
    });
  }

最后,您的FutureBuilder将更改为:

FutureBuilder<SakaryaAir>(
          future: _future,
          builder: (context, snapshot) {
            //Rest of your code
          }),

这是DartPad演示: https://dartpad.dev/2f937d27a9fffd8f59ccf08221b82be3

Here is a DartPad demo: https://dartpad.dev/2f937d27a9fffd8f59ccf08221b82be3

这篇关于在Flutter中以间隔自动获取Api数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆