在Flutter中以间隔自动获取Api数据

时间:2019-12-10 10:02:27

标签: json api flutter time dart

在我的flutter应用程序上,我试图显示更新数据。我成功地从weather api手动获取了数据。但是我需要每5秒不断获取数据。因此,它应该自动更新。这是我在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');
    }
  }
}

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

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

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

2 个答案:

答案 0 :(得分:3)

未来可以有2种状态:已完成或未完成。期货不能“进步”,但是流可以,因此对于您的用例,流更有意义。

您可以像这样使用它们:

Stream.periodic(Duration(seconds: 5)).asyncMap((i) => getSakaryaAir())

定期每5秒发出一次空事件,我们使用 asyncMap 将该事件映射到另一个流中,从而获取数据。

这是工作示例:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class ExamplePage extends StatelessWidget {
  Future<String> getSakaryaAir() async {
    String url =
        'https://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new';
    final response =
        await http.get(url, headers: {"Accept": "application/json"});

    return response.body;
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: Stream.periodic(Duration(seconds: 5))
          .asyncMap((i) => getSakaryaAir()), // i is null here (check periodic docs)
      builder: (context, snapshot) => Text(snapshot.data.toString()), // builder should also handle the case when data is not fetched yet
    );
  }
}

答案 1 :(得分:1)

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

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

Future< SakaryaAir> _future;

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

@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