我想在页面的initState中获取SharedPreferences值,并将该值传递给另一个返回Future的方法。但是,仅因为SharedPreferences返回的Future是其正常结果,所以我无法将其值传递给另一个方法。它总是返回“null”,这是我的SharedPref方法:
Future<String> getTenantId() async {
SharedPreferences appPreferences = await SharedPreferences.getInstance();
final tenantId = appPreferences.getString("tenantId");
if(tenantId == null) {
return null;
}
return tenantId;
}
在我的initState方法中:@override
void initState() {
// TODO: implement initState
super.initState();
final tenantId = getTenantId();
tenantId.then((value) => {
_debitInvoiceFuture = dInvoiceRep.getSingleDebitInvoiceById(widget.dId, value)
});
}
“dInvoiceRep.getSingleDebitInvoiceById(widget.dId,值)”这一行返回Future,我将它与FutureBuilder小部件一起使用来构建UI。还有另一种方法吗?
最佳答案
只需编写一种返回所需Future
的方法:
void initState() {
// TODO: implement initState
super.initState();
_debitInvoiceFuture = _getDebitInvoiceFuture();
}
Future<?> _getDebitInvoiceFuture() async { // figure out what future your getSingleDebitInvoiceById returns
final appPreferences = await SharedPreferences.getInstance();
final tenantId = await appPreferences.getString("tenantId");
return dInvoiceRep.getSingleDebitInvoiceById(widget.dId, tenantId)
}
关于flutter - 将SharedPreferences值传递给Flutter中的另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62792598/