0

我在我的项目中使用了包 http,因此,我将客户端的实例(来自包 http)作为依赖项,它是一个抽象类。那么,我应该如何使用正确的注释进行注释呢?在injectable 的文档中,有关于如何注册第三方依赖以及如何注册抽象类的信息。但是如何注册第三方抽象类呢?

这是我的代码

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();
    }
  }
}

我应该如何为第三方抽象类编写注册模块?

我确实在injectable的文档上看到了这个

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

但我不明白在我的代码中应该用什么替换 ThirdPartyImpl 。

4

1 回答 1

1

您不一定需要定义一个抽象类来注入您的依赖项。因此,在您的情况下,要注册第三方类,您可以使用相同的类型,而无需单独使用abstractandconcrete类。请参阅以下示例,了解如何注册Client从 http 包中导入的 http 类:


@module
abstract class YourModuleName {

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

Client然后,您可以使用您拥有的全局GetIt变量在任何地方使用http ,如下所示:

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

于 2021-12-01T18:16:45.480 回答