如何在Flutter中使用Injectable和get_it使用Inject String?

时间:2020-07-30 06:48:19

标签: flutter dart

 @LazySingleton()
 @ChopperApi(baseUrl:"/api")
 abstract class ChatApiService extends ChopperService { 
   
  @Post(path: "/logout")
  Future<Response> logout(
  @Body() Map<String, dynamic> body,);
  
  @factoryMethod
  static ChatApiService create(String accessToken){
   final client = ChopperClient(
    baseUrl: 'localhost:8000',
    services: [_$ChatApiService()],
    converter: JsonConverter(),
    client: http.IOClient(
     HttpClient()..connectionTimeout = const Duration(seconds: 60),
    ),
    interceptors: [
     HeadersInterceptor({
      'Accept': 'application/json',
      'Authorization':'Bearer $accessToken'
    }),
    HttpLoggingInterceptor()
   ]
 );
return _$ChatApiService(client);
}
}

运行构建运行程序时,消息框说factoryMethod依赖于String,这是不可注入的... 那你怎么注入String

1 个答案:

答案 0 :(得分:0)

通常,您可以使用模块注入原始类型或第三方类型

@module
abstract class RegisterModule{
//register the string as a named type
 @Named('accessToken')
 String get accessToken => "myAccessToken";
}

现在在您的工厂方法或构造函数中,使用@named注释您的可注入字符串

 @factoryMethod
  static ChatApiService create(@Named('accessToken') String accessToken){}