BaseConnectionManager<E extends Decodable> constructor

BaseConnectionManager<E extends Decodable>({
  1. required String baseUrl,
  2. required Map<String, String> constantHeaders,
  3. E decodeErrorFromMap(
    1. int statusCode,
    2. Map<String, dynamic> data
    )?,
  4. int? mapStatusCodeFromResponse(
    1. Map<String, dynamic>? data
    )?,
  5. bool onTokenExpiredRuleOverride(
    1. Response response
    )?,
  6. Future<String?> onTokenExpired()?,
  7. void onResponseReceived(
    1. Response response
    )?,
  8. bool returnCatchedErrorMessage = true,
  9. Duration timeout = const Duration(minutes: 1),
  10. bool persistCookies = false,
  11. 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,
});