Flutter - FutureBuilder 返回空快照,但未来实际上是返回数据

时间:2021-01-17 21:32:09

标签: flutter

我正在尝试从 API

获取数据

所以我使用了 Future 来做到这一点。问题是:未来实际上从这个 API 返回数据,因为如果我打印这些数据它可以工作,但是当我从快照中检索相同的数据时它返回 null。

这是检索数据的代码:

import 'dart:convert';

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

class NasaReportsApi {
  final String title;
  final String url;
  final DateTime publishedDate;
  final Map<String, dynamic> general;

  NasaReportsApi({this.title, this.url, this.publishedDate, this.general});

  factory NasaReportsApi.fromJson(Map<String, dynamic> json) {

    // it actually print this with data
    print(json['docs'][0]['title']);
    //
    
    return NasaReportsApi(
      general: json['docs'],
      title: json['docs'][0]['title'],
      url: json['docs'][0]['url'],
      publishedDate: json['docs'][0]['published_date']
    );
  }
}

Future<NasaReportsApi> fetchReports() async {
  // try for network issues
  try {
    final response = await http
            .get("https://spaceflightnewsapi.net/api/v1/reports?limit=1000?news_site=nasa?");

    // status code 200 means the get request is successful
    if (response.statusCode == 200) {
      return NasaReportsApi.fromJson(json.decode(response.body));
    } else
      throw Exception('Failed to load JSON');
  } catch (_) {
    return null;
  }
}

这就是我的 FutureBuilder:

 FutureBuilder<NasaReportsApi>(
    future: futureReports,
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.done) {
        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView.builder(
              itemCount: 1000,
              itemBuilder: (context, index) {
                return Container(
                  height: getHeight(context) / 20.0,
                  width: getWidth(context),
                  child: Card(
                    child: Padding(
                      padding: EdgeInsets.only(
                          top: getHeight(context) / 50.0,
                          left: getWidth(context) / 36.0,
                          right: getWidth(context) / 36.0),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment:
                                MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                               snapshot.data.general[index]['title'],
                                style: GoogleFonts.poppins(
                                    fontWeight: FontWeight.w500,
                                    fontSize: 17.0),
                              )
                            ],
                          )
                        ],
                      ),
                    ),
                  ),
                );
              }),
        );
      } else {
        return Container();
      }
    },
  ),

我没有设置快照没有数据时的条件来查看发生了什么。打印 snapshot.error 只是打印 null。我已经使用类似的 API 尝试了相同的 FutureBuilder,并且可以正常工作。

1 个答案:

答案 0 :(得分:0)

依靠 hasData 而不是连接状态会更好。

if (snapshot.hasData) {
    return Padding(
        padding: const EdgeInsets.all(8.0),
        child: ListView.builder(
        ...
}