-1

iam 将 Riverpod 与 dartz 一起使用,nad iam 面临一个问题,即当使用带有我的函数的未来提供程序时,我也无法使用其中任何一个,我如何通过错误处理隔离我想要从函数中检索的内容!

我的提供商代码:

final activeCourseProvider =
    FutureProvider.autoDispose.family<List<CourseModel>, int>((ref, yearId) {
  final _courseRepository = ref.watch(coursesRepositoryProvider);
  return _courseRepository.activeCourses(yearId);
});

我的功能代码:

Future<Either<ApiFailures, List<CourseModel>>> activeCourses(int yearId) async {
   try{ final response = await http.post(
        Uri.parse("http://msc-mu.com/api_verfication.php"),
        body: {"flag": "selectcourses", "year": "$yearId"});
if (response.statusCode == 200) {
        var l = json.decode(response.body) as List<dynamic>;
        var courses = l.map((e) => CourseModel.fromJson(e)).toList();
        return right(courses);
      } else {
        return left(ApiFailures.notFound());
      }
    } on SocketException {
      return left(ApiFailures.noConnection());
    } on HttpException {
      return left(ApiFailures.notFound());
    }
  }

弹出的错误是:The return type 'Future<Either<ApiFailures, List<CourseModel>>>' isn't a 'Future<List<CourseModel>>', as required by the closure's context.

4

2 回答 2

1

看来您的 ProvideractiveCourseProvider应该返回 a List<CourseModel>,而不是Either<ApiFailures, List<CourseModel>>.

您可以按如下方式使用fold该值:Either

final activeCourseProvider = FutureProvider.autoDispose.family<List<CourseModel>, int>((ref, yearId) {
  final _courseRepository = ref.watch(coursesRepositoryProvider);
  return _courseRepository.fold<List<CourseModel>>(
    (ApiFailures failure) => {
      // Handle failure
      return [];
    },
    (List<CourseModel> r) => r
  );
});

但是,您可能还希望您的 Provider 返回一个Either<ApiFailures, List<CourseModel>>值而不是List<CourseModel>. 如果您想ApiFailures在表示层中进一步处理,这可能会很有用。这取决于您的架构。

于 2021-08-21T21:14:35.267 回答
0

这是因为您声明该函数将返回 Either 结果:

Future<Either<ApiFailures, List<CourseModel>>>

但是当你传递类型时:

FutureProvider.autoDispose.family<List<CourseModel>

要么不处理,改变这个:

return _courseRepository.activeCourses(yearId);

final result= _courseRepository.activeCourses(yearId);
if(result.isRight()){
return result.gerOrElse(()=>null);
}else{
///handle left result
}
于 2021-08-21T16:35:45.493 回答