0

我目前没有 FutureProvider + shared_preferences 的实现:

class IdentityModel {
  final bool isLoggedIn;
  final int id;
  final String userName;
  final String avatarUrl;

  const IdentityModel({
    this.isLoggedIn = false,
    this.id,
    this.userName,
    this.avatarUrl,
  });
}

class IdentityNotifier extends StateNotifier<IdentityModel> {
  IdentityNotifier() : super(_initialState);

  static final _initialState = IdentityModel();

  void loginAction(MyCustomUserClass user) {
    state = IdentityModel(
      isLoggedIn: true,
      id: user.id,
      userName: user.userName,
      avatarUrl: user.avatarUrl,
    );
  }

  void logoutAction() {
    state = IdentityModel(
      isLoggedIn: false,
      id: null,
      userName: null,
      avatarUrl: null,
    );
  }
}

final identityProvider = StateNotifierProvider<IdentityNotifier>(
  (ref) => IdentityNotifier(),
);

我想使用shared_preferences包来保持状态,但我不太确定如何将我当前的实现转换FutureProvider为用作获取/设置shared_preferences用途的实现。async/await

我基本上想在应用程序启动时shared_preferences使用它的方法来“加载”来初始化通知程序,然后调用通知程序方法中的方法和.getshared_preferences setloginActionlogoutAction

4

1 回答 1

0

如果您的 IdentityNotifier 依赖于 Future 它应该是 StateNotifier<AsyncValue> 如果未来尚未加载或有错误,这允许您在 UI 上显示不同的信息。

class IdentityNotifier extends StateNotifier<AsyncValue<IdentityModel>> {
  IdentityNotifier({this.prefs}) : super(AsyncLoading());
  final SharedPreferences prefs;

  void init() {
    /// check user & get state from prefs
    state = AsyncData(IdentityModel(id:prefs.getInt("id")));
  }

  void loginAction(MyCustomUserClass user) {
    /// set info in prefs
    state = AsyncData(IdentityModel(
      isLoggedIn: true,
      id: user.id,
      userName: user.userName,
      avatarUrl: user.avatarUrl,
    ));
  }

  void logoutAction() {
    /// set info in prefs
    state = AsyncData(IdentityModel(
      isLoggedIn: false,
      id: null,
      userName: null,
      avatarUrl: null,
    ));
  }
}

使您的提供者依赖于未来的提供者:

final identityProvider = StateNotifierProvider<IdentityNotifier>((ref) {
  
  return ref.watch(_sharedPref).when(
      data: (prefs){
        final identityNotifier =  IdentityNotifier(prefs: prefs);
        identityNotifier.init();
        return identityNotifier;
      },
      loading: () => IdentityNotifier(),
      error: (_, __) => throw "error" /// throw or set an error state in your notifier
      );
  
});

final FutureProvider<SharedPreferences> _sharedPref =
    FutureProvider((ref) async => SharedPreferences.getInstance());

第一帧你的 IDNotifier 将被加载,你可以显示 CircularIndicator... 下一步当 sharedPref 实例被加载时,IdNotifier 被重新实例化为 pref 引用并且 init 方法设置你的用户数据

于 2021-02-15T21:43:12.703 回答