FutureBuilder未显示从服务器获取的json数据

时间:2020-06-10 00:22:54

标签: json flutter

我是新手,由于某种原因,futurebuilder不会显示从服务器获取的json数据;数据打印在调试控制台上,但未显示在UI中,我一遍又一遍更改代码,但始终得到相同的结果“出了点问题”

Future<List<Album>> getData(http.Client client) async {
List<Album> list;
String link = "https://extendsclass.com/api/json-storage/bin/efcedbd";
var res = await http
    .get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
print(res.body);
if (res.statusCode == 200) {
  dynamic data = json.decode(res.body);
  var rest = data["articles"] as List;
  print(rest);
  list = rest.map<Album>((dynamic json) => Album.fromJson(json)).toList();
}
print("List Size: ${list.length}");
return list;}
Future<List<Album>> transactionsFuture;
void initState() {
transactionsFuture = getData(http.Client());
super.initState();}

class Album {

final String id;

Album({this.id});

factory Album.fromJson(Map<String, dynamic> json) {
return Album(
  id: json['id'] as String,
);}}
body: FutureBuilder(
  future: transactionsFuture,
  builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
    if (snapshot.hasData) {
      // Data fetched successfully, display your data here
      return Column(
        children: <Widget>[
          Text(snapshot.data.id),

        ],
      );
    } else if (snapshot.hasError) {
      // If something went wrong
      return Text('Something went wrong...');
    }

    // While fetching, show a loading spinner.
    return CircularProgressIndicator();
  }
)

我的代码缺少什么吗?

1 个答案:

答案 0 :(得分:0)

您错误地实现了FutureBuilder和getData函数。使用FutureBuilder,您可以直接调用getData函数,而无需将该函数的返回值分配给代码中声明的变量。另外,删除您的initState()和fromJson() 试试这个:

Future<String> getData(http.Client client) async {
String link = "https://extendsclass.com/api/json-storage/bin/efcedbd";
var res = await http
    .get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
print(res.body);
if (res.statusCode == 200) {
  final data = json.decode(res.body);
}
return data["id"] ;}

您的构建小部件:

body: FutureBuilder(
  future: getData,
  builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
    if (snapshot.hasData) {
      // Data fetched successfully, display your data here
      return Column(
        children: <Widget>[
          Text(snapshot.data),
        ],
      );
    } else if (snapshot.hasError) {
      // If something went wrong
      return Text('Something went wrong...');
    }
    return CircularProgressIndicator();
  }
 ),