Jisho-Study-Tool/lib/bloc/search/search_bloc.dart

55 lines
1.6 KiB
Dart
Raw Normal View History

2020-07-09 20:06:48 +02:00
import 'dart:async';
import 'package:bloc/bloc.dart';
2020-08-17 11:15:32 +02:00
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
2021-08-03 22:02:42 +02:00
import 'package:jisho_study_tool/models/history/search.dart';
import 'package:jisho_study_tool/models/history/word_query.dart';
2020-07-09 20:06:48 +02:00
import 'package:meta/meta.dart';
2021-07-17 16:11:17 +02:00
import 'package:jisho_study_tool/bloc/database/database_bloc.dart';
2021-03-02 22:26:59 +01:00
import 'package:jisho_study_tool/services/jisho_api/jisho_search.dart';
2020-08-19 16:26:25 +02:00
import 'package:unofficial_jisho_api/parser.dart';
2020-07-09 20:06:48 +02:00
part 'search_event.dart';
part 'search_state.dart';
class SearchBloc extends Bloc<SearchEvent, SearchState> {
2021-07-17 16:11:17 +02:00
DatabaseBloc _databaseBloc;
SearchBloc(this._databaseBloc) : super(SearchInitial());
void addSearchToDB(searchString) {
if (_databaseBloc.state is DatabaseDisconnected)
throw DatabaseNotConnectedException;
(_databaseBloc.state as DatabaseConnected)
2021-08-03 22:02:42 +02:00
.database
.box<Search>()
.put(Search(timestamp: DateTime.now())
..wordQuery.target = WordQuery(
query: searchString,
));
2021-07-17 16:11:17 +02:00
}
2020-07-09 20:06:48 +02:00
@override
Stream<SearchState> mapEventToState(
SearchEvent event,
) async* {
2020-08-19 16:26:25 +02:00
if (event is GetSearchResults) {
yield SearchLoading();
try {
2021-07-17 16:11:17 +02:00
addSearchToDB(event.searchString);
2021-03-03 00:24:25 +01:00
final searchResults = await fetchJishoResults(event.searchString);
2021-08-03 22:02:42 +02:00
if (searchResults.meta.status == 200)
yield SearchFinished(searchResults.data!);
2020-08-19 16:26:25 +02:00
} on Exception {
yield SearchError('Something went wrong');
}
} else if (event is ReturnToInitialState) {
2020-08-24 23:46:04 +02:00
yield SearchInitial();
2020-08-19 16:26:25 +02:00
}
2020-07-09 20:06:48 +02:00
}
}