我一直在尝试从服务器获取数据并将其显示在futurebuilder的listview.builder中,但是listview仅在应用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;
});
}
这是我将来所说的地方。需要知道我要去哪里。
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),
),
]),
),
最佳答案
在您的代码中,您没有从return
块中调用_fetchData()
。
您的返回类型为Future
,您需要使用await
,并从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
的方法是返回Future
类型。指定您的返回类型Future<List< PosModelData>>
并返回Future
类型return sPref.then((s) {}
。请检查以下示例代码和
Futures
document进行dart异步编程。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');
}
});
});
关于android - 提取Json后无法刷新ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52942014/