trevorwang / retrofit.dart

retrofit.dart is an dio client generator using source_gen and inspired by Chopper and Retrofit.
https://mings.in/retrofit.dart/
MIT License
1.06k stars 241 forks source link

Add methods to the API class #644

Open feinstein opened 7 months ago

feinstein commented 7 months ago

I want to add a helper method to my api class, but if I try I get an error message from my compiler saying that method's implementation could not be found in the generated class that implements the abstract class I defined.

I got it to work by doing this:

@RestApi(baseUrl: 'https://api.bitbucket.org/2.0')
abstract class BitbucketRestDataSource {
  factory BitbucketRestDataSource(Dio dio) => _BitbucketRestDataSource._(dio);

  const BitbucketRestDataSource._();

  // That's my helper method that I want to use in the generated class.
  String createBasicCredentials({required String username, required String password}) {
    final String credentials = base64Encode(utf8.encode('$username:$password'));
    return 'Basic $credentials';
  }

I am basically creating a private constructor and calling the new generated constructor.

This works, but it's not documented anywhere, so it feels like a hack, and this functionality could cease to work at any time.

Could you please document how we can add helper methods to our API classes? Is this the best way to do it?

emintolgahanpolat commented 6 months ago

You can use extension or mixin

extension BitbucketRestDataSourceEx on BitbucketRestDataSource { void test() { print("test"); } }

feinstein commented 4 months ago

I want access to the dio instance, the only way I could find so far is by doing this ugly hack:

  factory AuthRemoteDataSource(Dio dio, {String? baseUrl}) => _AuthRemoteDataSource._(dio, dio, baseUrl: baseUrl);

  const AuthRemoteDataSource._(this.dio);

  final Dio dio;

...

 Future<Uint8List?> getImage(String url) async {
   // add code here that uses the dio instance.
  }

This declares a private constructor, and then I need to call the generated constructor repeting the dio twice, because it creates a dynamic parameter that's forwarded into the private constructor.