mirror of
https://github.com/pese-git/cherrypick.git
synced 2026-01-25 22:36:44 +00:00
implement example
This commit is contained in:
16
examples/postly/lib/data/model/post_model.dart
Normal file
16
examples/postly/lib/data/model/post_model.dart
Normal file
@@ -0,0 +1,16 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'post_model.freezed.dart';
|
||||
part 'post_model.g.dart';
|
||||
|
||||
@freezed
|
||||
class PostModel with _$PostModel {
|
||||
const factory PostModel({
|
||||
required int id,
|
||||
required String title,
|
||||
required String body,
|
||||
}) = _PostModel;
|
||||
|
||||
factory PostModel.fromJson(Map<String, dynamic> json) =>
|
||||
_$PostModelFromJson(json);
|
||||
}
|
||||
17
examples/postly/lib/data/network/json_placeholder_api.dart
Normal file
17
examples/postly/lib/data/network/json_placeholder_api.dart
Normal file
@@ -0,0 +1,17 @@
|
||||
import 'package:retrofit/retrofit.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../model/post_model.dart';
|
||||
|
||||
part 'json_placeholder_api.g.dart';
|
||||
|
||||
@RestApi(baseUrl: 'https://jsonplaceholder.typicode.com/')
|
||||
abstract class JsonPlaceholderApi {
|
||||
factory JsonPlaceholderApi(Dio dio, {String baseUrl}) = _JsonPlaceholderApi;
|
||||
|
||||
@GET('/posts')
|
||||
Future<List<PostModel>> getPosts();
|
||||
|
||||
@GET('/posts/{id}')
|
||||
Future<PostModel> getPost(@Path('id') int id);
|
||||
}
|
||||
32
examples/postly/lib/data/post_repository_impl.dart
Normal file
32
examples/postly/lib/data/post_repository_impl.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
import 'package:dartz/dartz.dart';
|
||||
import '../domain/entity/post.dart';
|
||||
import '../domain/repository/post_repository.dart';
|
||||
import 'network/json_placeholder_api.dart';
|
||||
|
||||
class PostRepositoryImpl implements PostRepository {
|
||||
final JsonPlaceholderApi api;
|
||||
|
||||
PostRepositoryImpl(this.api);
|
||||
|
||||
@override
|
||||
Future<Either<Exception, List<Post>>> getPosts() async {
|
||||
try {
|
||||
final posts = await api.getPosts();
|
||||
return Right(posts
|
||||
.map((e) => Post(id: e.id, title: e.title, body: e.body))
|
||||
.toList());
|
||||
} catch (e) {
|
||||
return Left(Exception(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<Exception, Post>> getPost(int id) async {
|
||||
try {
|
||||
final post = await api.getPost(id);
|
||||
return Right(Post(id: post.id, title: post.title, body: post.body));
|
||||
} catch (e) {
|
||||
return Left(Exception(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user