spebbe / dartz

Functional programming in Dart
MIT License
749 stars 60 forks source link

Fixing subtype errors #76

Closed Torone closed 3 years ago

Torone commented 3 years ago

I'm new to Flutter and also on Dartz package but I cannot find any solution online that would answer my question...

What I did is not rocket science, I'm just testing a very simple endpoint that return { message: 'success' } and what I did so far is the following:

class StatusHelper {
  final api = StatusApi();
  Future<Either<Glitch, Status>> getStatus() async {
    final apiResult = await api.getStatus();
    return apiResult.fold((l) {
      return Left(NoInternetGlitch());
    }, (r) {
      final status = Status.fromMap(jsonDecode(r));
      return Right(status);
    });
  }
}

And

class StatusApi {
  String endpoint = 'myApi.net';

  Future<Either<Exception, String>> getStatus() async {
    try {
      final uri = Uri.https(endpoint, 'status').toString();
      final response = await dio.get(uri);
      print('RESPONSE: ${response.data}');
      return Right(response.data);
    } catch (e) {
      print('ERROR: $e');
      return (Left(e));
    }
  }
}

Very simple and it also return the correct data when used. The point is that I don't like to see errors and warnings on my terminal and I wish to fix every single thing. Actually, I have the success message and 2 errors when I create the request:

flutter: RESPONSE: {message: success}
flutter: ERROR: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: type '_TypeError' is not a subtype of type 'Exception'
#0      StatusApi.getStatus (package:flutter_test/models/services/status_api.dart:15:20)
<asynchronous suspension>
#1      StatusHelper.getStatus (package:flutter_test/models/helper/status_helper.dart:11:23)
<asynchronous suspension>

How can I fix those 2 errors? What I'm doing wrong?

Thanks for your help in advance!

spebbe commented 3 years ago

Hi @Torone!

This doesn't look related to dartz. While I don't have access to all the type information, I believe you have multiple type errors in the code above. I would highly recommend using https://pub.dev/packages/pedantic, or better yet, https://pub.dev/packages/extra_pedantic. These packages provide good analyzer settings and should highlight unsafe type assumptions with at least e and response.data above, as well as provide helpful information about the actual types involved.

Hope that helps!

Torone commented 3 years ago

Thanks for your reply and useful hint!