我想使用 FutureBuilder 来检查 url 是否为 png 图像,然后构建一个或两个图像(在列表中)。但不知怎的,当我打印它时,Future 总是返回 null...
结果是应用程序总是使用两个 CachedNetworkImage 构建列表视图,这不是我想要的。如果 URL 是图像,它应该只使用该 url 构建一个 CachedNetworkImage,如果不是,它应该更改 url 并构建一个包含 2 个图像的列表视图。
child: new FutureBuilder(
future: _getImages(widget.imgUrl),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return new Text('Press button to start');
case ConnectionState.waiting:
return new Text('Awaiting result...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else {
print(snapshot.data);
if (snapshot.data == "image/png") {
return new SingleChildScrollView(
child: new CachedNetworkImage(
imageUrl: widget.imgUrl,
placeholder: new Center(
child: new AdaptiveProgressIndicator()),
),
);
} else {
return new ListView(
children: <Widget>[
new CachedNetworkImage(
imageUrl:
widget.imgUrl.split('.png')[0] + '-0.png',
placeholder: new Center(
child: new AdaptiveProgressIndicator()),
),
new CachedNetworkImage(
imageUrl:
widget.imgUrl.split('.png')[0] + '-1.png',
)
],
);
}
}
}
}),
),
));
}
Future<String> _getImages(String url) async {
await http.get(url).then((result) {
return result.headers['content-type'];
});
}
Run Code Online (Sandbox Code Playgroud)
这段代码有点奇怪。
Future<String> _getImages(String url) async {
await http.get(url).then((result) {
return result.headers['content-type'];
});
}
Run Code Online (Sandbox Code Playgroud)
async允许您避免then(在大多数情况下)。
代码应该是:
Future<String> _getImages(String url) async {
var result = await http.get(url);
// for debugging only
print('statusCode: ${result.statusCode}');
var contentType = result.headers['content-type'];
print('content-type: $contentType');
return contentType;
}
Run Code Online (Sandbox Code Playgroud)
这样您还可以检查请求是否确实提供了结果。
| 归档时间: |
|
| 查看次数: |
5970 次 |
| 最近记录: |