[英]How to init state of widget variable with Future string in flutter
我必須使用存儲在 StoredProcedure 中的值初始化 widget 變量的 state。
void initState() {
widget.query = fetchMake();
super.initState();
}
Future<String> fetchMake() async{
final prefs = await SharedPreferences.getInstance();
return prefs.getString(key);
query.toString();
}
但問題是它無法將該值分配給查詢變量並且顯示錯誤value to type future string cannot assign to string flutter
我怎樣才能做到這一點?
你可以試試:
String query;
void initState() {
super.initState();
fetchMake().then((value) {
setState(() {
query = value;
});
});
}
Future<String> fetchMake() async{
final prefs = await SharedPreferences.getInstance();
return prefs.getString(key);
}
1、不能用widget.query設置state 。
2、在Widget的state上創建變量查詢。
3, fetchMake是一個異步 function => 使用then等待結果。
fetchMake 是異步的,因此您必須將 await 放在調用該方法的位置,但它不會工作,因為您是在 initState 中調用它。
因此,您必須僅在該 function 中分配 widget.query 變量值。 此外,當您獲取數據時,您必須調用 setState,因此您收到的數據會反映在 ui 中。
除此之外,您還必須檢查查詢是 null 還是在您使用它的地方,因為當第一次調用構建方法時,它不會有任何數據。
String query;
void initState() {
fetchMake();
super.initState();
}
fetchMake() async{
final prefs = await SharedPreferences.getInstance();
setState((){
query = prefs.getString(key) ?? 'default';
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.