簡體   English   中英

使用 FutureBuilder 顯示 API 數據

[英]Displaying API data using FutureBuilder

我想從復雜的 json API 中獲取數據,並在 Flutter 未來構建器中顯示數據。

這是 json 的示例

 {
    "hours": [
        {
            "time": "2021-03-23T00:00:00+00:00",
            "waveHeight": {
                "icon": 1.35,
                "meteo": 1.25,
                "noaa": 1.28,
                "sg": 1.25
            }
        },
{
            "time": "2021-03-23T00:00:00+00:00",
            "waveHeight": {
                "icon": 1.35,
                "meteo": 1.25,
                "noaa": 1.28,
                "sg": 1.25
            }
        },
    ],
}

這是從 API 獲取數據的 function

Future getJsonData() async {
    String url2 =
        'https://api.stormglass.io/v2/weather/point?lat=5.9774&lng=80.4288&params=waveHeight&start=2021-03-23&end2021-03-24';
    
    String apiKey =
        '0242ac130002-248f8380-7a54-11eb-8302-0242ac130002';
    print('0');

    
    Response response = await get(Uri.parse(url2),
        headers: {HttpHeaders.authorizationHeader: apiKey});

   
    final _extractedData = json.decode(response.body) as Map<String, dynamic>;

    List<Wave> _data = [];
    List<Wave> _fetchedData = [];

    _extractedData['hours'].forEach((value) {
      _fetchedData.add(Wave(
        time: value['time'],
        icon: value['icon'],
        meteo: value['meteo'],
        noaa: value['noaa'],
        sg: value['sg'],
      ));
    });

    _data = _fetchedData;

    print(_data);

    return _data;
  }

數據在控制台中打印如下

/flutter ( 4879): [Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', Instance of 'Wave', In

下面是futurebuilder

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("API"),
      ),
      body: Container(
        child: FutureBuilder(
            future: getJsonData(),
            builder: (context, AsyncSnapshot<dynamic> snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data[0]['time']);
              } else {
                return CircularProgressIndicator();
              }
            }),
      ),
    );
  }

當我運行應用程序時,顯示以下錯誤

The following NoSuchMethodError was thrown building FutureBuilder<dynamic>(dirty, state: _FutureBuilderState<dynamic>#e19f8):
Class 'Wave' has no instance method '[]'.
Receiver: Instance of 'Wave'
Tried calling: []("time")

以下是波class

class Wave {
  final String time;
  final double icon;
  final double meteo;
  final double noaa;
  final double sg;

  Wave({
    this.time,
    this.icon,
    this.meteo,
    this.noaa,
    this.sg,
  });

  factory Wave.fromJson(Map<String, dynamic> json) {
    return Wave(
        time: json['time'],
        icon: json['icon'],
        meteo: json['mateo'],
        noaa: json['noaa'],
        sg: json['sg']);
  }
}

我想獲取數據並在 flutter 列表視圖中打印

這是因為您從 getJsonData 返回的數據不是 map 而是 model class 您創建的“WAVE”。

基本上要訪問您的“時間”,您需要更改代碼:

return Text(snapshot.data[0]['time']);

return Text(snapshot.data[0].time);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM