BambinoUA
BambinoUA

Reputation: 7100

Flutter: How to implement non-standard code flow using `injectable` package?

Let's say I need this:

class EndpointProvider {
  String getEndpoint(String trigger) {
    // skipped for clarity
  }
}

class MyHttpClient implements BaseHttpClient {
  MyHttpClient(this.baseUrl, [String accessToken = '']);  
}

class MyRemoteDataProvider extends BaseDataProvider {
  MyRemoteDataProvider(this.httpClient)

  final BaseHttpClient httpClient;
}

The current code flow is:

final endpointProvider = EndpointProvider();
final endpoint = endpointProvider.getEndpoint('trigger');
final accessToken = getTokenFromStorage() ?? '';
final httpClient = MyHttpClient(endpoint.url, accessToke );
final dataProvider = MyRemoteDataProvider(httpClient);
dataProvider.do();

Is it posssible to implement this using injectable?

Upvotes: 0

Views: 232

Answers (1)

Camillo bucciarelli
Camillo bucciarelli

Reputation: 352

You can try this:

@lazySingleton
class EndpointProvider {
  String getEndpoint(String trigger) {
    return 'https://api.example.com/$trigger';
  }
}

@LazySingleton(as: BaseHttpClient)
class MyHttpClient implements BaseHttpClient {
  final String baseUrl;
  MyHttpClient(EndpointProvider endpointProvider, [@Named('accessToken') String accessToken]) : baseUrl = endpointProvider.getEndpoint('my_endpoint');
}

@lazySingleton
class MyRemoteDataProvider extends BaseDataProvider {
  MyRemoteDataProvider(this.httpClient)

  final BaseHttpClient httpClient;
}

and in the same file of injectable configuration you can put:

@module
abstract class Module {
  @Named('accessToken')
  String get accessToken => '';
}

Upvotes: 1

Related Questions