Jisho-Study-Tool/lib/bloc/kanji/kanji_bloc.dart

41 lines
1.1 KiB
Dart
Raw Normal View History

2020-07-09 20:06:48 +02:00
import 'dart:async';
2020-07-13 15:18:17 +02:00
import './kanji_event.dart';
import './kanji_state.dart';
2020-07-09 20:06:48 +02:00
2020-07-13 15:18:17 +02:00
import 'package:bloc/bloc.dart';
2021-03-02 22:26:59 +01:00
import 'package:jisho_study_tool/services/jisho_api/kanji_search.dart';
import 'package:jisho_study_tool/services/kanji_suggestions.dart';
2020-07-09 20:06:48 +02:00
2020-07-13 21:21:33 +02:00
export './kanji_event.dart';
export './kanji_state.dart';
2020-07-09 20:06:48 +02:00
class KanjiBloc extends Bloc<KanjiEvent, KanjiState> {
2020-07-13 15:18:17 +02:00
2020-07-09 20:06:48 +02:00
KanjiBloc() : super(KanjiSearchInitial());
@override
2021-03-02 22:26:59 +01:00
Stream<KanjiState> mapEventToState(KanjiEvent event)
async* {
2020-07-13 15:18:17 +02:00
if (event is GetKanji) {
yield KanjiSearchLoading();
2020-07-13 15:18:17 +02:00
try {
2021-03-03 00:24:25 +01:00
final kanji = await fetchKanji(event.kanjiSearchString);
if (kanji.found) yield KanjiSearchFinished(kanji: kanji);
2020-07-16 14:08:35 +02:00
else yield KanjiSearchError('Something went wrong');
2020-07-13 15:18:17 +02:00
} on Exception {
yield KanjiSearchError('Something went wrong');
}
} else if (event is GetKanjiSuggestions) {
final suggestions = kanjiSuggestions(event.searchString);
yield KanjiSearchInput(suggestions);
} else if (event is ReturnToInitialState) {
yield KanjiSearchInitial();
2020-07-13 15:18:17 +02:00
}
2020-07-09 20:06:48 +02:00
}
}