flutter - 将SharedPreferences值传递给Flutter中的另一个方法

标签 flutter dart sharedpreferences

我想在页面的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/

相关文章:

android - Android Gradle插件仅支持Kotlin Gradle插件1.3.10及更高版本

flutter - AssetImage 和 ExactAssetImage 有什么区别?

dart - Dart中的元编程性能

android - 如何使用 flutter 中的键删除/清除共享首选项?

flutter - 来自同一StatefulWidget的新实例的行为

Flutter TextField 获取选定文本

dart - 如何在嵌套模板中查找元素

flutter - 在上载到Firebase之前先调整图像的大小

android - SharedPreferences 重启后不保存所有数据

dart - 多个小部件与 TabController 使用相同的 GlobalKey