Home > Back-end >  Using injectable for third party abstract class in flutter
Using injectable for third party abstract class in flutter

Time:12-02

I have used package http in my project and thus, I have Client's instance (which comes from package http) as a dependency, which is an abstract class. So, how should I annotate with proper annotations? In injectable's documentation, there is information on how to register third-party dependencies and how to register abstract classes. But how can I register third-party abstract class?

This is my code

class TokenValueRemoteDataSourceImpl implements TokenValueRemoteDataSource {
  TokenValueRemoteDataSourceImpl(this.client);

  final http.Client client;

  @override
  Future<TokenValueModel> getAuthToken({
    required EmailAddress emailAddress,
    required Password password,
  }) async {
    final emailAddressString = emailAddress.getOrCrash();
    final passwordString = password.getOrCrash();
    const stringUrl = 'http://127.0.0.1:8000/api/user/token/';

    final response = await client.post(
      Uri.parse(stringUrl),
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(
        {
          'email': emailAddressString,
          'password': passwordString,
        },
      ),
    );
    if (response.statusCode == 200) {
      return TokenValueModel.fromJson(
        json.decode(response.body) as Map<String, dynamic>,
      );
    } else {
      throw ServerException();
    }
  }
}

How should I write my register module for a third-party abstract class?

I did see this on injectable's documentation

@module  
abstract class RegisterModule {  
  @singleton  
  ThirdPartyType get thirdPartyType;  
  
  @prod  
  @Injectable(as: ThirdPartyAbstract)  
  ThirdPartyImpl get thirdPartyType;  
}  

But I didn't understand what I should replace ThirdPartyImpl with in my code.

CodePudding user response:

You don't necessarily need to define an abstract class to inject your dependencies. So for in your case, to register a third-party class, you can use the same type without having an abstract and concrete class separately. See the below example of how to register the http Client class that is imported from the http package:


@module
abstract class YourModuleName {

  @lazySingleton // or @singleton 
  http.Client get httpClient => http.Client(); 
}

Then you can use the http Client anywhere using the global GetIt variable you have, like this:

yourGetItVariableName.get<http.Client>(); or GetIt.I.get<http.Client>();

  • Related