如何防止在图像已经通过互联网下载后发出更多的URL请求


var alreadyDdl = false; 
getLogoUrl(context) async {
if(!alreadyDdl) {
final db = Localstore.instance;
final data = db.collection('inputs').doc("1").get();
var database = (await data)["content"].toString();
var form = new DGForm("project/getwebsitelogo", {"database": database});
var ret = await form.urlGET(context);
ResponseObject responseObject =
ResponseObject.fromJson(json.decode(ret.body));
print("hola");
var hola = (responseObject.datas[0][0].toString());
bandeauDuClient = hola;
print(hola);
return hola;
}
}
getLogoUrl(context).then((val) {
setState(() => 
logoUrl = val
);
alreadyDdl = true;
});

永远不会在小部件构建中向我显示服务器下载的图像

(logoUrl != null) ? Image.network(logoUrl): Image.asset('assets/none.png') 

因此,当我从代码中删除所有alreadyDdl变量时,它将每15毫秒发出一个http请求。我想在图像真正下载后停止http请求。。。

您可以使用future生成器根据与future交互的最新快照创建小部件。您可以将它与上面建议的cached_network_image包结合使用。

下面是一个示例代码,演示了这一点:

import "package:flutter/material.dart";
//Your other imports...
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyApp();
}
}
class _MyApp extends State<MyApp> {
var db;
@override
initState() {
db = Localstore.instance;
}
getLogoUrl(context) async {
final data = db.collection('inputs').doc("1").get();
var database = (await data)["content"].toString();
var form = new DGForm("project/getwebsitelogo", {"database": database});
var ret = await form.urlGET(context);
ResponseObject responseObject =
ResponseObject.fromJson(json.decode(ret.body));
print("hola");
var hola = (responseObject.datas[0][0].toString());
bandeauDuClient = hola;
print(hola);
return hola;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: getLogoUrl(context),
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// if we got our data
if (snapshot.hasData) {
return CachedNetworkImage(
imageUrl: snapshot.data,
progressIndicatorBuilder: (context, url, downloadProgress) => 
CircularProgressIndicator(value: downloadProgress.progress),
errorWidget: (context, url, error) => Icon(Icons.error),
);
} else {
// If we probably got an error check snapshot.hasError
return Center(
child: Text(
'${snapshot.error} occurred',
style: TextStyle(fontSize: 18),
),
);
}
} else {
return const CircularProgressIndicator();
}
},
),
);
}
}

注意:永远不要在构建方法中进行网络调用,因为构建方法通常每秒调用60次以进行渲染。在initState或像FutureBuilder这样的小部件中进行网络调用,为您处理这些事情

相关内容

  • 没有找到相关文章

最新更新