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

Şan*_*baş 10 api time json dart flutter

在我的颤振应用程序中,我试图显示更新数据。我成功地手动从天气 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');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我发现这样一个片段可以从中受益:

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

可能我需要用这个代码片段来包装和调用 FutureBuilder,但我无法理解如何去做。

pr0*_*ist 12

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

您可以像这样使用它们:

Stream.periodic(Duration(seconds: 5)).asyncMap((i) => getSakaryaAir())
Run Code Online (Sandbox Code Playgroud)

周期性每 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
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Vic*_*ele 5

您可以重构您FutureBuilder的使用Future变量而不是调用FutureBuilder. 这将要求您使用 aStatefulWidget并且您可以在您的未来设置initState并通过调用setState.

所以你有一个未来的变量字段,如:

Future< SakaryaAir> _future;
Run Code Online (Sandbox Code Playgroud)

所以你initState看起来像这样:

@override
  void initState() {
    super.initState();
    setUpTimedFetch();
  }
Run Code Online (Sandbox Code Playgroud)

其中setUpTimedFetch定义为

  setUpTimedFetch() {
    Timer.periodic(Duration(milliseconds: 5000), (timer) {
      setState(() {
        _future = getSakaryaAir();
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

最后,您FutureBuilder将更改为:

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

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