获取后无法刷新列表视图 Json
Unable to refresh listview after fetching Json
我一直在尝试从服务器获取数据并将其显示在 futurebuilder 中的 listview.builder 中,但是列表视图仅在应用 setstate() 后更新,请帮助卡住了一段时间。
Future<dynamic> _fetchData() async {
sPref.getUserId().then((onValue) {
userIds = onValue;
});
sPref.getAuthToken().then((val) {
token = val;
var body = {
'userId': '$userIds',
};
var client = http.Client();
var response = http.Request(
'POST', Uri.parse('http://example.net/api/fetchJson'));
response.headers["Authorization"] = "Bearer $token";
response.bodyFields = body;
print(response.headers);
client.send(response).then((response) {
return http.Response.fromStream(response);
}).then((res) {
return res.body;
}).then((body) {
return json.decode(body);
}).then((body) {
print(body.toString());
var datas = body['data'];
if (body['status'] == 'success') {
list = (datas as List)
.map((data) => new PosModelData.fromJson(data))
.toList();
return list;
} else {
print('failed');
}
});
return list;
});
}
这是我在 future.Need 中调用它的地方,以了解我哪里出错了。
body: FutureBuilder(
future: _fetchData(),
builder: (context, data) {
switch (data.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
// if (data.hasError)
// return new Text('Error: ${data.error}');
// else
return ListView.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return Container(
padding: EdgeInsets.symmetric(
horizontal: 6.0, vertical: 4.0),
child: Card(
elevation: 10.0,
child: Column(children: <Widget>[
ListTile(
title: Text(list[index].firstName),
subtitle: list[index].phone != null
? Text(list[index].phone)
: Text('Not mentioned'),
trailing: trailingText(index),
),
]),
),
在您的代码中,您没有从 _fetchData()
块中调用 return
。
您的 return 类型是 Future
,您需要使用 await
,指定您的 return 类型 List<PosModelData>
和 return
async
块
Future<List<PosModelData>> _fetchData() async {
final response = await http.Request('POST', Uri.parse('http://example.net/api/fetchJson'));
final list = ... convert response to list
return list;
}
然后你将从回调builder: (context, data) {}
.
中获取列表
请检查 this 示例。
已更新 1
不使用 async
和 await
,另一种使用 Future
的方法是 returning Future
类型。指定您的 return 类型 Future<List< PosModelData>>
和 return Future
类型
return sPref.then((s) {}
.
dart异步编程请参考以下示例代码和Futures
document
Future<List<PosModelData>> _fetchData() {
return Future.wait([sPref.getUserId(), sPref.getAuthToken()]).then((data) {
userIds = data.first;
token = data[1];
var body = {
'userId': '$userIds',
};
var client = http.Client();
var response = http.Request(
'POST', Uri.parse('http://example.net/api/fetchJson'));
response.headers["Authorization"] = "Bearer $token";
response.bodyFields = body;
print(response.headers);
return client.send(response).then((response) {
return http.Response.fromStream(response);
}).then((res) {
return res.body;
}).then((body) {
return json.decode(body);
}).then((body) {
print(body.toString());
var datas = body['data'];
if (body['status'] == 'success') {
list = (datas as List)
.map((data) => new PosModelData.fromJson(data))
.toList();
return list;
} else {
print('failed');
}
});
});
我一直在尝试从服务器获取数据并将其显示在 futurebuilder 中的 listview.builder 中,但是列表视图仅在应用 setstate() 后更新,请帮助卡住了一段时间。
Future<dynamic> _fetchData() async {
sPref.getUserId().then((onValue) {
userIds = onValue;
});
sPref.getAuthToken().then((val) {
token = val;
var body = {
'userId': '$userIds',
};
var client = http.Client();
var response = http.Request(
'POST', Uri.parse('http://example.net/api/fetchJson'));
response.headers["Authorization"] = "Bearer $token";
response.bodyFields = body;
print(response.headers);
client.send(response).then((response) {
return http.Response.fromStream(response);
}).then((res) {
return res.body;
}).then((body) {
return json.decode(body);
}).then((body) {
print(body.toString());
var datas = body['data'];
if (body['status'] == 'success') {
list = (datas as List)
.map((data) => new PosModelData.fromJson(data))
.toList();
return list;
} else {
print('failed');
}
});
return list;
});
}
这是我在 future.Need 中调用它的地方,以了解我哪里出错了。
body: FutureBuilder(
future: _fetchData(),
builder: (context, data) {
switch (data.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
// if (data.hasError)
// return new Text('Error: ${data.error}');
// else
return ListView.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return Container(
padding: EdgeInsets.symmetric(
horizontal: 6.0, vertical: 4.0),
child: Card(
elevation: 10.0,
child: Column(children: <Widget>[
ListTile(
title: Text(list[index].firstName),
subtitle: list[index].phone != null
? Text(list[index].phone)
: Text('Not mentioned'),
trailing: trailingText(index),
),
]),
),
在您的代码中,您没有从 _fetchData()
块中调用 return
。
您的 return 类型是 Future
,您需要使用 await
,指定您的 return 类型 List<PosModelData>
和 return
async
块
Future<List<PosModelData>> _fetchData() async {
final response = await http.Request('POST', Uri.parse('http://example.net/api/fetchJson'));
final list = ... convert response to list
return list;
}
然后你将从回调builder: (context, data) {}
.
请检查 this 示例。
已更新 1
不使用 async
和 await
,另一种使用 Future
的方法是 returning Future
类型。指定您的 return 类型 Future<List< PosModelData>>
和 return Future
类型
return sPref.then((s) {}
.
dart异步编程请参考以下示例代码和Futures
document
Future<List<PosModelData>> _fetchData() {
return Future.wait([sPref.getUserId(), sPref.getAuthToken()]).then((data) {
userIds = data.first;
token = data[1];
var body = {
'userId': '$userIds',
};
var client = http.Client();
var response = http.Request(
'POST', Uri.parse('http://example.net/api/fetchJson'));
response.headers["Authorization"] = "Bearer $token";
response.bodyFields = body;
print(response.headers);
return client.send(response).then((response) {
return http.Response.fromStream(response);
}).then((res) {
return res.body;
}).then((body) {
return json.decode(body);
}).then((body) {
print(body.toString());
var datas = body['data'];
if (body['status'] == 'success') {
list = (datas as List)
.map((data) => new PosModelData.fromJson(data))
.toList();
return list;
} else {
print('failed');
}
});
});