[英]Flutter FutureBuilder not triggered when onPressed of ElevatedButton runs
我遇到了一个问题,当 ElevatedButton 的 onPress 运行时,我的 FutureBuilder 小部件没有触发。
在该方法中,我调用了一个 http 服务。 所以未来是在 onPress 中设定的。
这是 ElevatedButton 片段:
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
minimumSize: Size(size.width / 30,size.height / 15),
shadowColor: Colors.redAccent,
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(15.0),
)
),
onPressed: () {
FocusScope.of(context).unfocus();
_future = _searchRoutes.findProductsByNameAndCity(
createFilterProducts(_productNameController.text,
_cityNameController.text,
_ufController.text,
int.parse(_itensPerPageController.text),
_orderByController.text),
_authScreenRoutes.getLocalJwtToken()
);
},
child: Icon(Icons.search),
),
findProductsByNameAndCity()
方法只返回一个 List 并且它正在工作。
以下是 FutureBuilder:
Expanded(
child: FutureBuilder<List<Product>>(
future: _future,
builder: (context, snapshot) {
if(snapshot.hasData){
if(snapshot.data!.length <=0){
return Container(
alignment: Alignment.center,
width: size.width,
height: size.height,
child: setText("Oops, ainda não temos esse produto nessa cidade.", padding / 1.5),
);
}else{
return Padding(
padding: sidePadding,
child: Container(
width: size.width,
height: size.height,
child: ListView.builder(
itemCount: snapshot.data!.length ,
itemBuilder: (context, index){
return ProductBox(
product: snapshot.data![index],
);
},
),
)
);
}
}else if(snapshot.connectionState == ConnectionState.waiting){
return Container(
alignment: Alignment.center,
width: size.width,
height: size.height,
child: CircularProgressIndicator(),
);
}else if (!snapshot.hasData){
return Container(
alignment: Alignment.center,
width: size.width,
height: size.height,
child: setText("Pesquise um produto.", padding / 1.5),
);
}else{
return Container(
alignment: Alignment.center,
width: size.width,
height: size.height,
child: CircularProgressIndicator(),
);
}
}
)
),
我知道 Http 调用正在工作,因为我进行了调试,当 ElevatedButton 中的断点将我带到方法findProductsByNameAndCity()
内部时,我看到了我正在等待接收的项目。
我不明白为什么 FutureBuilder 不显示这些项目。
我究竟做错了什么?
你错过了
setState<\/code>
试试这个:
onPressed: () {
FocusScope.of(context).unfocus();
_future = _searchRoutes.findProductsByNameAndCity(
createFilterProducts(_productNameController.text,
_cityNameController.text,
_ufController.text,
int.parse(_itensPerPageController.text),
_orderByController.text),
_authScreenRoutes.getLocalJwtToken()
);
setState((){});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.