clean_network 1.0.8+1 clean_network: ^1.0.8+1 copied to clipboard
A Wrapper for Dio to make network calls in a clean way. It supports REST and GraphQL with clean architecture and cache support.
Clean Network #
CleanNetwork
is wrapper around dio and gql to make it easier to make network requests.
Get started #
1. Add dependency #
dependencies:
clean_network: latest
2. Import package #
import 'package:clean_network/clean_network.dart';
3. Initialize in dependency injection #
import 'package:clean_network/clean_network.dart';
import 'package:injectable/injectable.dart';
@module
abstract class ThirdPartyModules {
@lazySingleton
CleanNetwork get network => CleanNetwork(
options: const CleanBaseOptions(
baseUrl: 'https://jsonplaceholder.typicode.com',
headers: {
'Content-Type': 'application/json',
},
loggerOptions: LoggerOptions(
enable: true,
request: true,
response: true,
),
),
);
}
4. Create remote service #
import 'package:clean_network/clean_network.dart';
import 'package:example/src/features/posts/data/models/post_model.dart';
import 'package:injectable/injectable.dart';
abstract class PostSource {
CleanResponse<List<PostModel>> getPosts();
CleanResponse<PostModel> getSinglePost(int id);
}
@LazySingleton(as: PostSource)
class PostSourceImpl extends BaseSource implements PostSource {
PostSourceImpl(super.client);
@override
CleanResponse<List<PostModel>> getPosts() {
return get(
'/posts',
onSuccess: PostModel.fromJsonList,
);
}
@override
CleanResponse<PostModel> getSinglePost(int id) {
return get(
'/posts/$id',
onSuccess: (response) => PostModel.fromJson(response),
);
}
}
5. Create base repository for handling network errors that can be extended by other repositories #
if you want your errors handling in repository level you can skip this step and extends BaseRepository directly in your repository
import 'package:clean_network/clean_network.dart';
import 'package:example/src/core/errors/app_error.dart';
import 'package:fpdart/fpdart.dart';
typedef AppResponse<T> = EitherResponse<AppError, T>;
class AppBaseRepository extends BaseRepository<AppError> {
@override
AppError errorConverter(ApiException exception) {
return AppError(exception.toString());
}
}
5. Create repository #
import 'package:example/src/core/network/base.dart';
import 'package:example/src/features/posts/data/models/post_model.dart';
import 'package:example/src/features/posts/data/source/post_source.dart';
import 'package:example/src/features/posts/domain/repository/post_repository.dart';
import 'package:injectable/injectable.dart';
@LazySingleton(as: PostRepository)
class PostRepositoryImpl extends AppBaseRepository implements PostRepository {
final PostSource _postSource;
PostRepositoryImpl(this._postSource);
@override
AppResponse<List<PostModel>> getPosts() {
return handleNetwork(_postSource.getPosts);
}
@override
AppResponse<PostModel> getSinglePost(int id) {
return handleNetwork(
() => _postSource.getSinglePost(id),
);
}
}