我正在尝试使用FutureBuilder显示无限列表。我想在不同的.dart文件中使用模型和服务,因此我需要在FutureBuilder中注入服务。我认为服务无法返回列表的问题,但我不知道为什么。代码是
模型
class Datameter {
int idAgrupacion;
int nroSerie;
String fecha;
///
double latitud;
double longitud;
String contador;
String sensor;
Datameter(
{this.idAgrupacion,
this.nroSerie,
this.fecha,
///
this.latitud,
this.longitud,
this.contador,
this.sensor});
factory Datameter.fromJson(json) => new Datameter(
nroSerie: json["nro_serie"],
idAgrupacion: json["id_agrupacion"],
fecha: json["fecha"],
//
latitud: json["latitud"],
longitud: json["longitud"],
contador: json["contador"],
sensor: json["sensor"],
);
}
服务
static Future<Datameter> getDatameters(dropdown) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final token = prefs.getString('token');
final response = await http.get(
'http://192.168.3.64:8080/datameter/agrupacion/info?agrupacion=' +
dropdown +
'&limite=0',
headers: {
HttpHeaders.authorizationHeader: "Token " + token
}).catchError((error) {
print(error.toString());
});
if (response.statusCode == 200) {
var responseJson = json.decode(response.body);
return responseJson["body"].map((item) => Datameter.fromJson(item)).toList();
}
return null;
}
查看
FutureBuilder(
future: DatameterService.getInstalations("2"),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return snapshot.data; ListView.separated(
separatorBuilder: (context, index) => Divider(
color: Colors.grey,
),
itemCount: snapshot.data.length,
itemBuilder: (context, i) {
return ListTile(
leading: Icon(FontAwesomeIcons.tint,
size: 24, color: Colors.black),
trailing: Text(DateFormat('yyyy/MM/dd HH:mm')
.format(DateTime.fromMillisecondsSinceEpoch(
snapshot.data[i]['fecha']))
.toString()),
onTap: null,
title: Text(
snapshot.data[i]['nro_serie'],
));
});
} else {
return CircularProgressIndicator();
}
}),
问题:返回'type DatameterList 类型不是'Widget'类型的子类型
所以:使用FutureBuilder显示列表的最正确方法是什么?
答案 0 :(得分:1)
builder函数应该返回一个Widget,就像您已经注释掉的一样:
FutureBuilder(
future: DatameterService.getInstalations("2"),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return ListView.separated(
separatorBuilder: (context, index) => Divider(
color: Colors.grey,
),
itemCount: snapshot.data.length,
itemBuilder: (context, i) {
return ListTile(
leading: Icon(FontAwesomeIcons.tint, size: 24, color: Colors.black),
trailing: Text(DateFormat('yyyy/MM/dd HH:mm')
.format(DateTime.fromMillisecondsSinceEpoch(
snapshot.data[i]['fecha'])
).toString()
),
onTap: null,
title: Text(
snapshot.data[i]['nro_serie'],
),
);
});
} else {
return CircularProgressIndicator();
}
}),