[英]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.