【问题标题】:Pass SharedPreferences value to another method in Flutter将 SharedPreferences 值传递给 Flutter 中的另一个方法
【发布时间】:2020-10-28 17:37:38
【问题描述】:

我想在页面的 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, value)" 此行返回 Future,我将它与 FutureBuilder 小部件一起使用来构建 UI。还有其他方法吗?

【问题讨论】:

    标签: flutter dart sharedpreferences


    【解决方案1】:

    试试这个

    @override
    
          void initState() {
            // TODO: implement initState
            super.initState();
            
            Future<String> tenantId = Future(getTenantId());
            tenantId.then((value) => {
              _debitInvoiceFuture = Future (dInvoiceRep.getSingleDebitInvoiceById(widget.dId, value));
            });
            
          }
    

    【讨论】:

      【解决方案2】:

      当我尝试在 initState 中使用未来时,我使用 Future

      Future.delayed(Duration.zero, () async {
        _debitInvoiceFuture = await dInvoiceRep.getSingleDebitInvoiceById(widget.dId, value)
      });
      

      【讨论】:

        【解决方案3】:

        只需编写一个返回您需要的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)
        } 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-05
          • 1970-01-01
          • 2020-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-13
          相关资源
          最近更新 更多