我在我的專案中使用了包 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。
uj5u.com熱心網友回復:
您不一定需要定義抽象類來注入您的依賴項。因此,對于您的情況,要注冊第三方類,您可以使用相同的型別,而無需單獨使用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>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/371761.html
上一篇:Flutter溢位截止
下一篇:顫振卡高度不適用于卡頂
