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.