簡體   English   中英

如何使用 shared_preferences 庫實現 Flutter Riverpod FutureProvider?

[英]How to implement Flutter Riverpod FutureProvider with shared_preferences library?

我目前沒有 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 package 保留 state,但我不太確定如何將我當前的實現轉換為使用FutureProvider的實現,因為shared_preferences使用async/await來獲取/設置。

我基本上想從shared_preferences中“加載”,使用它的get方法在應用程序啟動時初始化通知程序,然后在通知程序方法loginActionlogoutAction中調用shared_preferences set方法。

如果您的 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 方法設置你的用戶數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM