BaseConnectionManager<E extends Decodable> constructor
BaseConnectionManager<E extends Decodable> ({
- required String baseUrl,
- required Map<
String, String> constantHeaders, - E decodeErrorFromMap()?,
- int? mapStatusCodeFromResponse()?,
- bool onTokenExpiredRuleOverride(
- Response response
- Future<
String?> onTokenExpired()?, - void onResponseReceived(
- Response response
- bool returnCatchedErrorMessage = true,
- Duration timeout = const Duration(minutes: 1),
- bool persistCookies = false,
- Client? client,
Initialise a ConnectionManager to manage API and network calls.
It is suggested to initialize it as a Provider or a Singleton to use a single instance of it all through the app.
The type E
can be specified to define a custom model for error responses.
Example
// Create the provider
class NetworkProvider {
final String baseUrl;
// Connection Manager definition
final _connectionManager = ConnectionManager<CustomError>(
baseUrl: baseUrl,
constantHeaders: {"Content-Type": "application/json"},
decodeErrorFromMap: CustomError.fromMapError,
onTokenExpired: () async {
return await refreshToken(); // refreshToken() is not a method of this package
},
onResponseReceived: (response) {
print(response.body);
},
);
// Connection Manager getter
ConnectionManager<CustomError> get connectionManager => _connectionManager;
}
// Use the provider
class MyApp extends StatelessWidget {
@override build(BuildContext context) {
return Provider(
create: (context) => NetworkProvider(
baseUrl: "https://test.com/api",
),
child: Builder(
builder: (context) {
var networkProvider = context.read<NetworkProvider>();
return Text(networkProvider.baseUrl);
}
),
);
}
}
Implementation
BaseConnectionManager({
required this.baseUrl,
required this.constantHeaders,
this.decodeErrorFromMap,
this.mapStatusCodeFromResponse,
this.onTokenExpiredRuleOverride,
this.onTokenExpired,
this.onResponseReceived,
this.returnCatchedErrorMessage = true,
this.timeout = const Duration(minutes: 1),
this.persistCookies = false,
this.client,
});