从 Future 函数返回/设置值

时间:2021-07-18 09:50:21

标签: flutter dart future

如何摆脱“异步编程”循环?我是否需要编写所有使用设备上值作为 Future 的方法?

我可以从外部调用 addPassword(),但仍然需要等待,直到它被设置(Future 函数)。我只想像任何其他方法一样返回这些值。

我的尝试:

我如何在设备上存储值:

import 'package:shared_preferences/shared_preferences.dart';
class StorageConnector {
  static Future setInt(String key, int value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setInt(key, value);
  }
  static Future getInt(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getInt(key);
  }
}

我如何从设备接收先前写入的值:

class Account{
  void addPassword(int password){ //i dont want to use await/async, because of this later functions
    StorageConnector.setInt("passwords", password);
  }

  int getAtPassword(int pos) { //Attention: doesn't compile
    /* I have tried this: */
    StorageConnector.getInt("passwords").then((value) { return value;});
    /* and this: */
    return StorageConnector.getInt("passwords");
  }
}

有类似的问题,但不幸的是,我无法正确理解/应用它们。

类似:FutureBuilder、.then(function)、外部函数

0 个答案:

没有答案