[英]FutureBuilder is not displaying json data fetched from server
i am new to flutter, for some reason futurebuilder is not displaying json fetched data from server;我是 flutter 的新手,出于某种原因,futurebuilder 没有显示 json 从服务器获取的数据; the data is printed on debug console but it is not displayed in UI, i changed my code over and over but i always get the same outcome "something went wrong"
数据打印在调试控制台上,但未显示在 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();
}
)
is my code missing something?我的代码缺少什么吗?
You implemented your FutureBuilder and getData function incorrectly.您错误地实施了 FutureBuilder 和 getData function。 With FutureBuilder, you can directly call the getData function without assigning that function's return value to the variable declared in your code.
使用 FutureBuilder,您可以直接调用 getData function 而无需将该函数的返回值分配给代码中声明的变量。 Also, remove your initState() and fromJson() Try this:
另外,删除你的 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"] ;}
Your build Widget:您的构建小部件:
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();
}
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.