'Why loadInitTopStory method called after calling loaded state in flutter?
HackerNewsLoadedState is called before HackerNewsLoadingState and it loads all data from API but does not integrate to _topStories list as well as store data to _topstories after calling HackerNewsLoadedState.
@override
Stream<HackerNewsState> mapEventToState(HackerNewsEvent event) async* {
if (event is FetchHackerNewsEvent) {
yield HackerNewsLoadingState();
try {
_loadInitTopStories();
yield HackerNewsLoadedState(story: _topStories);
} catch (e) {
yield HackerNewsErrorState(message: e.toString());
}
}
}
void _loadInitTopStories() async {
try {
_topStoryIds.addAll(await _repository.loadTopStoryIds());
} catch (e) {
_topStoriesStreamController.sink.addError('Unknown Error');
return;
}
loadMoreTopStories(pageSize: INIT_PAGE_SIZE);
}
void loadMoreTopStories({int pageSize = PAGE_SIZE}) async {
if (_isLoadingMoreTopStories) return;
_isLoadingMoreTopStories = true;
final storySize = min(_currentStoryIndex + pageSize, _topStoryIds.length);
for (int index = _currentStoryIndex; index < storySize; index++) {
try {
_topStories.add(await _repository.loadStory(_topStoryIds[index]));
} catch (e) {
print('Failed to load story with id ${_topStoryIds[index]}');
}
}
_currentStoryIndex = _topStories.length;
_topStoriesStreamController.sink.add(_topStories);
_isLoadingMoreTopStories = false;
}
Solution 1:[1]
Found the solution it's return void but it's a mistake, it returns Stream
Stream<HackerNewsState> _loadInitTopStories() async* {
yield HackerNewsLoadingState();
try {
_topStoryIds.addAll(await repository.loadTopStoryIds());
} catch (e) {
_topStoriesStreamController.sink.addError('Unknown Error');
return;
}
yield* loadMoreTopStories(pageSize: INIT_PAGE_SIZE);
yield HackerNewsLoadedState(story: _topStories);
}
Stream<HackerNewsState> loadMoreTopStories(
{int pageSize = PAGE_SIZE}) async* {
if (_isLoadingMoreTopStories) return;
_isLoadingMoreTopStories = true;
final storySize = min(_currentStoryIndex + pageSize, _topStoryIds.length);
for (int index = _currentStoryIndex; index < storySize; index++) {
try {
_topStories.add(await repository.loadStory(_topStoryIds[index]));
} catch (e) {
print('Failed to load story with id ${_topStoryIds[index]}');
}
}
_currentStoryIndex = _topStories.length;
_topStoriesStreamController.sink.add(_topStories);
_isLoadingMoreTopStories = false;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jahidul Islam |