簡體   English   中英

在 flutter 中使用可注入的第三方抽象 class

[英]Using injectable for third party abstract class in flutter

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. 那么,我應該如何使用正確的注釋進行注釋呢? injectable 的文檔中,有關於如何注冊第三方依賴以及如何注冊抽象類的信息。 但是如何注冊第三方抽象 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 ZEFE90A8E6034A7C840E888 導入的 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>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM