#Flutter/Riverpod – 在使用AsyncNotifier时,是否只能调用错误?

huangapple go评论44阅读模式
英文:

#Flutter/Riverpod - Is it possible to call only error when using AsyncNotifier?

问题

我正在使用Riverpod作为我的Flutter项目的状态管理,并且目前正在处理身份验证服务。我有一个AuthNotifier扩展AsyncNotifier的问题是当我像这样调用AuthService时:

Future<void> logout() async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      return await authService.logout();
    });
    state.when(
      data: (data){},
      error: (error, stackTrace){
        ref.read(errorProvider.notifier).createException(exception: error.toString(), errorTitle: "Logout Error");
      },
      loading: (){},
    );
  }

我只在state.when中使用了error,但我也有这段未使用的代码。

我尝试查看state或state.when的方法,但无法找到任何东西,可能是因为答案不在那里,或者是因为我没有看到它。如果有人对在Notifier内部处理错误有其他建议,我愿意听取建议。

英文:

I am using riverpod as state management for my flutter project and am currently working on auth services. I am having AuthNotifier extending AsyncNotifier. The problem is when i make a call to the AuthService for example like that:

Future&lt;void&gt; logout() async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      return await authService.logout();
    });
    state.when(
      data: (data){},
      error: (error, stackTrace){
        ref.read(errorProvider.notifier).createException(exception: error.toString(), errorTitle: &quot;Logout Error&quot;);
      },
      loading: (){},
    );
  }

I am only using the error in the state.when but i also have this unused code.

I tried looking for at the methods of state or state.when but couldn't find anything either because the answer is not there or because i didn't see it. If anyone has alternative on handling the error inside the Notifier i am open to suggestions.

答案1

得分: 1

使用whenOrNull/mapOrNullmaybeWhen/maybeMap来处理部分状态,例如:

final Object? newState = state.whenOrNull(
      error: (error, stackTrace){
        ...
      },
    );

// 或者

final Object newState = state.whenOrNull(
      orElse: () => ...,
      error: (error, stackTrace){
        ...
      },
    );
英文:

Use whenOrNull/mapOrNull or maybeWhen/maybeMap to handle only some states, for example:

final Object? newState = state.whenOrNull(
      error: (error, stackTrace){
        ...
      },
    );

// or

final Object newState = state.whenOrNull(
      orElse: () =&gt; ...,
      error: (error, stackTrace){
        ...
      },
    );

huangapple
  • 本文由 发表于 2023年5月29日 22:02:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76358003.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定