Generic Usecase Flutter

Table Of Content
Hello everyone! Today, I want to show you the usage of generic usecases in flutter with riverpod.
Base UseCase
We will start with usecase
.
Creating base usecase
Firstly, we need to create a base class for usecase, and we will extend it for different usecases.
dart
abstract class UseCaseBase<T, Params> { const UseCaseBase(); }
We also need no-params
class. It's an optional class. You don't need to use it every time.
For no parameters:
dart
class NoParams {}
Creating base usecases for Future
and Stream
For Future
:
dart
abstract class FutureUseCase<T, Params> extends UseCaseBase<T, Params> { const FutureUseCase(); Future<T> call(Params params); }
And for Stream
:
dart
abstract class StreamUseCase<T, Params> extends UseCaseBase<T, Params> { const StreamUseCase(); Stream<T> call(Params params); }
So now, we have usecases
for Stream
case and Future
case.
Usage
We will apply the above usecase where we need. Firstly, if you want to create getting posts from database usecase, we should use Stream
for returning data.
GetPosts Usecase
dart
class GetPosts implements StreamUseCase<List<Post>>, NoParams> { final PostRepository repo; const GetPosts(this.repo); @override Stream<List<Post>> call(NoParams params) => repo.watchAllPosts(); }
But, if you want to use just Future
,
dart
class GetPosts implements FutureUseCase<List<Post>>, NoParams> { final PostRepository repo; const GetPosts(this.repo); @override Future<List<Post>> call(NoParams params) => repo.getAllPosts(); }
CreatePost Usecase
Let's create a post. Firstly, we need some parameters to create post.
dart
class CreatePostParams { final String title; final String? description; final String author; const CreatePostParams({ required this.title, this.description, required this.author, }); }
And then, create a usecase for creating post.
dart
class CreatePost implements FutureUseCase<Post?>, CreatePostParams> { final PostRepository repo; const CreatePost(this.repo); @override Future<Post?> call(CreatePostParams params) async { return repo.createPost( title: params.title, description: params.description, author: params.author, ); } }
The last thing we need to do is using in our presentation layer or application layer if you are using application layer separately.
I will show you in next article for this usage in presentation layer. Thank you for reading my blogs.