当Futurebuilder停止返回筹码时,我很难弄清楚如何停止循环。
对于我的 future 构建者,我会收到一个字符串列表,然后从该字符串所在的索引中创建一个芯片,然后将其放入一个列表中,以供以后在程序中使用。
extractFutureChip(_response, index){
return FutureBuilder<String>(
future: _response, // if you mean this method well return image url
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if(snapshot.connectionState == ConnectionState.done){
var jsonString = snapshot.data;
//print(jsonString);
List terms = jsonDecode(jsonString);
if(index>=terms.length){
return Container(height: 0.0,width: 0.0,);
}
//print(terms);
Chip return_val = Chip(
backgroundColor: Colors.orange[900],
labelStyle: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
label: Text(terms[index])
);
return return_val;
}else if(snapshot.connectionState == ConnectionState.waiting){
return Chip(
backgroundColor: Colors.grey[700],
labelStyle: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
label: Text("Loading")
);
}
return Chip(
backgroundColor: Colors.black,
labelStyle: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
label: Text("ERROR")
);
}
);
}
我曾尝试引发并捕获异常,但这没有用,
我尝试过如果对象类型不匹配,请打破while循环。
当前有效的解决方案是设置大量的最大筹码,然后如果索引超过将来列表中的项目数,则返回空容器。
while(true){
if(ind>200){
break;
}
var chip = extractFutureChip(tags2, ind);
list_of_skills.add(chip);
//print(list_of_skills);
ind+=1;
}
但是这里有两个问题,如果某人拥有超过200件物品,
当大多数响应中的字符串少于5个时,搜索大量内容实际上是效率低下的。
最佳答案
因此,我认为您可能误解了FutureBuilder的目的:1)每当传入的将来更改时,FutureBuilder
只会更新您的窗口小部件树; 2)意味着返回窗口小部件(树)。因此,一旦准备就绪,就可以从_response
obj构建列表的最简单方法是在方法内部使用 Wrap
小部件。
例如。
return FutureBuilder<String>(
future: _response, // if you mean this method well return image url
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.done){
var jsonString = snapshot.data;
List terms = jsonDecode(jsonString);
return Wrap(
children: List.generate(terms.length, (index) => Chip(
backgroundColor: Colors.orange[900],
labelStyle: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
label: Text(terms[index])
)),
);
} else if (...) { ... }
else return Container();
});
另一方面,如果您想拆分异步请求以获得将来的数据和小部件构建,那么您可能应该使用某种初始化函数来代替FutureBuilder:
Future<List<String>> someFunc() async {
try {
var jsonString = await _response;
// do some more manipulation or other stuff
return jsonDecode(jsonString);
} on Exception catch (e) {
// TODO you can catch exceptions coming from the Future here
}
}
(然后使用返回的字符串列表构建筹码)
关于flutter - 如何在Futter循环中停止Futurebuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60480119/