等待future.then()完成-扑

时间:2019-11-14 07:35:10

标签: flutter dart

我具有以下应返回SharedPreference实例的函数:

SharedPreferences get sp {
    Future<SharedPreferences> prefs = SharedPreferences.getInstance();
    SharedPreferences temp;
    prefs.then((value) { temp = value; });
    return temp; //This is running immediately before completion and returning null 
}

我来自iOS背景。有DispatchGroup可以帮助我们解决相同的问题:

SharedPreferences get sp {
        Future<SharedPreferences> prefs = SharedPreferences.getInstance();
        SharedPreferences temp;
        //dispatchGroup.enter()
        prefs.then((value) { 
           temp = value; 
           //dispatchGroup.leave()
        });
        //dispatchGroup.wait()
        return temp; //This is running immediately before completion 
   }

我们如何使future.then()等待其完成,然后将控制权传递给下一行?飘动中是否有类似于iOS的DispatchGroup的东西?

更新:

我正在寻找一种获取SharedPreferences实例的方法,以便在下面的示例中使用它:

bool get isLoggedIn => sp.getBool('IsLoggedIn');
set isLoggedIn(bool loggedIn) => sp.setBool('IsLoggedIn', loggedIn);

String get userPhone => sp.getString('UserPhone');
set userPhone(String phone) => sp.setString('UserPhone', phone);

更新2

以下是到目前为止的完整类,用于管理整个应用程序中的SharedPreferences:

class UserDefaults
{
  SharedPreferences sp;

  //Singleton
  UserDefaults._internal();
  static final UserDefaults _instance = UserDefaults._internal();
  factory UserDefaults() {
    _instance.initPreferences();
    return _instance;
  }

  initPreferences() async {
    sp = await SharedPreferences.getInstance();
  }

  /*
  SharedPreferences get sp {
    Future<SharedPreferences> prefs = SharedPreferences.getInstance();
    SharedPreferences temp;
    prefs.then((value) { temp = value; });
    return temp;
  }
  */

  bool get isLoggedIn => sp.getBool('IsLoggedIn');
  set isLoggedIn(bool loggedIn) => sp.setBool('IsLoggedIn', loggedIn);

  String get userPhone => sp.getString('UserPhone');
  set userPhone(String phone) => sp.setString('UserPhone', phone);
}

当从main()函数调用UserDefaults()。isLoggedIn时,这不起作用,并给出错误:'null调用了'getBool'。我猜是因为initPreferences需要一些时间。

2 个答案:

答案 0 :(得分:1)

将代码放入异步功能:

SharedPreferences sp

loadPrefs() async {
    sp = await SharedPreferences.getInstance();
}

bool get isLoggedIn => sp.getBool('IsLoggedIn');
set isLoggedIn(bool loggedIn) => sp.setBool('IsLoggedIn', loggedIn);

String get userPhone => sp.getString('UserPhone');
set userPhone(String phone) => sp.setString('UserPhone', phone);

在初始化时调用loadPrefs()

答案 1 :(得分:0)

你为什么不简单地使用这个:

Future<SharedPreferences> getSp() async{
  return await SharedPreferences.getInstance();
}