๐ฎFuture data
Future data management using Pulse
Usage
Pulse-X gives you full control of Future data with PulseXFutureViewModel, PulseXFutureBuilder, PulseXState and PulseXReactions.
PulseXFutureViewModel gives you features such as api handling, api data state control and business logic which are separated from UI.
PulseXFutureBuilder makes UI reactive. It takes view model and builder function as parameters. You can show various widgets based on Future State which can be called via
viewModel.status.PulseXState is a simple class that has four states - initial,loading, loaded,error. You can control each of them.
PulsXeReactions are side effects inspired from Mobx state management. In Pulse, you can only use side effects with Future data. ๐ฅฒ
For example project, we'll use dummy data from https://dummyjson.com.
First of all, create a Post data model.
import 'dart:convert';
Post postsFromJson(String str) => Post.fromJson(json.decode(str));
String postsToJson(Post data) => json.encode(data.toJson());
class Post {
int id;
String title;
String body;
int userId;
List<String> tags;
int reactions;
Post({
required this.id,
required this.title,
required this.body,
required this.userId,
required this.tags,
required this.reactions,
});
factory Post.fromJson(Map<String, dynamic> json) => Post(
id: json["id"],
title: json["title"],
body: json["body"],
userId: json["userId"],
tags: List<String>.from(json["tags"].map((x) => x)),
reactions: json["reactions"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"body": body,
"userId": userId,
"tags": List<dynamic>.from(tags.map((x) => x)),
"reactions": reactions,
};
}
Then, create an abstract service class so that you can easily attach, detach and switch concrete services.
After that, create a concrete service class that extends ApiService class.
Now, you are ready to create View Model that extends PulseXFutureViewModel.
In UI, you have to take care of two things - reactions and future data. First I'll extract widgets as classes to be clear.
ErrorMessage widget class
Here, I'll show you one thing. If you don't wanna pass your ViewModel down the widget tree, Pulse-X provides you with PulseXStateManager.of<YourViewModel>(context) method.
PostList widget class
Then, show data based on your state.
As the last step, you only need to create a reaction based on state. If state is loaded, then show a snackbar.
Remove TODOand add this in your didChangeDependencies() method.
๐๐ป Tada! Now, you understand how pulse works and will be able to use it in your projects.
Complete source code can be found here. https://github.com/YeLwinOo-Steve/posts
Last updated