Home > OS >  How to log response from api in cubits?
How to log response from api in cubits?

Time:11-26

I am new at flutter and trying to get response from api in cubit/bloc but can't do this

Api returns 200 statusCode and data response like this:

{"success":true,"userId":770,"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NzcwLCJlbWFpbCI6ImpiYmZkakBnbWFpbC5jb20iLCJwcm9kdWN0SWQiOjEwLCJleHAiOjE2Njk0NjA0Nzl9.pmees83Cf8lF-YMvZKEw9BYFyJrcmYCjlESpY51PVMo","refreshToken":"62b00668-c2b4-4e07-a888-1b3405e979de"}

This is my function(signUp) in cubit file:

  Future<Response> signUp() async {
    try {
      final Response response =  await _apiService.signUp( // Here flutter returns: Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Response<dynamic>'
        email: state.email ?? "",
        password: state.password ?? "",
        firstName: state.firstName ?? "",
        lastName: state.lastName ?? "",
        genderUuid: state.genderUuid ?? "",
        ageGroupUuid: state.ageGroupUuid ?? "",
        countryUuid: state.countryUuid ?? ""
      );
      Map<String, dynamic > data = Map<String, dynamic>.from(jsonDecode(response.data));
      log(data.toString());
      return response.data;
    } on DioError catch (ex) {
      log("ex ==== ${ex.toString()}");
      return ex.response!;
    } catch (e) {
      // log(e.toString());
      rethrow;
    }
  }
}

I call signUp in widget like this:

final res = BlocProvider.of<AuthCubit>(context).signUp();

log(res.toString()) // Instance of 'Future<Response<dynamic>>'

How can I log response in cubits? I don't understand why I can't do this

CodePudding user response:

You have to await the call to signUp().

final res = await BlocProvider.of<AuthCubit>(context).signUp();

But I'm guessing you have a small error in the return type of the method. You are returning response.data but the return type is Response. So you should probably change Future<Response> signUp() to Future<Data_type_of_Response.data> signUp()

  • Related