0

I want to use Either to store result in BlocBuilder. According to result I want to show specific Widget. But using Either will throw exception that BlocBuilder returned null. I debugged that code and fold branch was called correctly, so it should return Widget. I don't understand how it could return null.

Code:

...
else if (state is Loaded) {
  final badgeOrFailure = state.profile.getBadgeByOrgId(orgId);
  badgeOrFailure.fold((err) {
       return MessageDisplay(
         message: err.message,
       );
  }, (badge) {
      return BadgeWidget(
       desc: badge.desc,
       code: badge.code,
     );
   });
...

Profile code:

Either<BadgeNotFoundFailure, Badge> getBadgeByOrgId(int orgId) {
    try {
      if (badges != null && badges.isNotEmpty) {
        return Right(badges.firstWhere((element) => element.orgId == orgId));
      } else {
        log('badges are empty');
        return Left(BadgeNotFoundFailure());
      }
    } on Exception catch (_) {
      return Left(BadgeNotFoundFailure());
    }
  }
martin1337
  • 2,384
  • 6
  • 38
  • 85
  • please make sure that `state.profile.` is null-safe by using `state.profile?.getBadgeByOrgId`. can you please share whole code-block related to this BLoC so that I can try to share an answer? – Yilmaz Guleryuz Aug 20 '20 at 07:47
  • profile is not null. I added nullcheck but same result – martin1337 Aug 20 '20 at 07:53

1 Answers1

0

I think that you need an explicit return, for example
return badgeOrFailure.fold(...

Can you please try it?

Yilmaz Guleryuz
  • 9,313
  • 3
  • 32
  • 43
  • This worked, but I have to keep inner returns aswell. Kinda weird that it cant return Widget from inside of fold method on its own. Because according to this syntax I logically think I want to return not Widget but Either. – martin1337 Aug 20 '20 at 10:09
  • that's right, inner returns must stay as well. p.s. i haven't done functional prog inside Dart, but similar situation happens when you use async calls and inner returns gets lost. so this led me to assume similar case for your error as well. – Yilmaz Guleryuz Aug 20 '20 at 10:10
  • are you using `dartz` package for functional programming? – Yilmaz Guleryuz Aug 20 '20 at 10:14