Last active
June 4, 2019 05:25
-
-
Save felangel/0b5fff3f6c7ec708311acdc983472e07 to your computer and use it in GitHub Desktop.
[flutter_infinite_list] post bloc mapEventToState
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@override | |
Stream<PostState> mapEventToState(PostEvent event) async* { | |
if (event is Fetch && !_hasReachedMax(currentState)) { | |
try { | |
if (currentState is PostUninitialized) { | |
final posts = await _fetchPosts(0, 20); | |
yield PostLoaded(posts: posts, hasReachedMax: false); | |
} | |
if (currentState is PostLoaded) { | |
final posts = await _fetchPosts(currentState.posts.length, 20); | |
yield posts.isEmpty | |
? currentState.copyWith(hasReachedMax: true) | |
: PostLoaded( | |
posts: currentState.posts + posts, hasReachedMax: false); | |
} | |
} catch (_) { | |
yield PostError(); | |
} | |
} | |
} | |
bool _hasReachedMax(PostState state) => | |
state is PostLoaded && state.hasReachedMax; | |
Future<List<Post>> _fetchPosts(int startIndex, int limit) async { | |
final response = await httpClient.get( | |
'https://jsonplaceholder.typicode.com/posts?_start=$startIndex&_limit=$limit'); | |
if (response.statusCode == 200) { | |
final data = json.decode(response.body) as List; | |
return data.map((rawPost) { | |
return Post( | |
id: rawPost['id'], | |
title: rawPost['title'], | |
body: rawPost['body'], | |
); | |
}).toList(); | |
} else { | |
throw Exception('error fetching posts'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment