在 flutter 中使用可注入的第三方摘要 class

Using injectable for third party abstract class in flutter

我在我的项目中使用了包 http,因此,我将客户端的实例(来自包 http)作为依赖项,这是一个抽象 class。那么,我应该如何使用适当的注释进行注释呢? 在injectable's documentation, there is information on how to register third-party dependencies and how to register abstract classes。但是如何注册第三方摘要class?

这是我的代码

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

我应该如何为第三方摘要编写注册模块class?

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

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

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

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


@module
abstract class YourModuleName {

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

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

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