'Flutter Injectable Inject a Third Party Dependency
I've been spinning my wheels for hours on the simple question of how to inject http.Client
into a flutter class when using injectable. They reference doing this in a module (as suggested in this post), but I can't figure that out either.
This is my file (abstract and concrete classes):
import 'dart:convert';
import 'package:get_it/get_it.dart';
import 'package:http/http.dart' as http;
import 'package:injectable/injectable.dart';
import 'package:myapp_flutter/core/errors/exceptions.dart';
import 'package:myapp_flutter/data/models/sample_model.dart';
abstract class ISampleRemoteDataSource {
/// Throws a [ServerException] for all error codes.
Future<SampleModel> getSampleModel(String activityType);
}
@Injectable(as: ISampleRemoteDataSource)
class SampleRemoteDataSourceImpl extends ISampleRemoteDataSource {
final http.Client client;
final baseUrl = "https://www.boredapi.com/api/activity?type=";
final headers = {'Content-Type': 'application/json'};
SampleRemoteDataSourceImpl({@factoryParam required this.client});
@override
Future<SampleModel> getSampleModel(String activityType) async {
Uri uri = Uri.parse(baseUrl + activityType);
GetIt.I.get<http.Client>();
final response = await client.get(uri, headers: headers);
if (response.statusCode == 200) {
return SampleModel.fromJson(json.decode(response.body));
} else {
throw ServerException();
}
}
}
I thought declaring it as a factory param in the constructor would do it, but I was wrong. Declaring the abstract class as a module doesn't do it (and seems very wrong, also). I just don't know.
Solution 1:[1]
You will have to register them as module as described below https://pub.dev/packages/injectable#Registering-third-party-types
Solution 2:[2]
This should work:
First implement a register module file
@module
abstract class RegisterModule {
//add http client
@lazySingleton
http.Client get httpClient => http.Client();
}
class $RegisterModule extends RegisterModule {}
Then, after generating injection.config.dart
file your http Client should be mentioned in initGetIt
class
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | M Afzal |
Solution 2 | olanow20 |