Jisho-Study-Tool/lib/view/screens/history.dart

77 lines
2.9 KiB
Dart
Raw Normal View History

2020-07-09 22:17:10 +02:00
import 'package:flutter/material.dart';
2021-07-17 16:11:17 +02:00
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jisho_study_tool/bloc/database/database_bloc.dart';
2021-08-03 22:02:42 +02:00
import 'package:jisho_study_tool/models/history/search.dart';
2021-07-19 01:49:18 +02:00
import 'package:jisho_study_tool/view/components/history/kanji_search_item.dart';
2021-08-03 22:02:42 +02:00
import 'package:jisho_study_tool/view/components/history/phrase_search_item.dart';
import 'package:jisho_study_tool/view/components/history/date_divider.dart';
import 'package:jisho_study_tool/objectbox.g.dart';
2020-07-09 22:17:10 +02:00
2020-07-13 23:41:31 +02:00
class HistoryView extends StatelessWidget {
2020-07-09 22:17:10 +02:00
@override
Widget build(BuildContext context) {
2021-07-17 16:11:17 +02:00
return BlocBuilder<DatabaseBloc, DatabaseState>(
builder: (context, state) {
if (state is DatabaseDisconnected)
throw DatabaseNotConnectedException();
2021-08-03 22:02:42 +02:00
return StreamBuilder(
stream: ((state as DatabaseConnected).database.box<Search>().query()
..order(Search_.timestamp, flags: Order.descending))
.watch(triggerImmediately: true)
.map((query) => query.find()),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) return Container();
return ListView.separated(
itemCount: snapshot.data.length + 1,
itemBuilder: (context, index) {
if (index == 0) return Container();
Search search = snapshot.data[index - 1];
if (search.isKanji()) {
return KanjiSearchItem(
result: search.kanjiQuery.target!,
timestamp: search.timestamp,
);
}
return PhraseSearchItem(
search: search.wordQuery.target!,
timestamp: search.timestamp,
);
},
separatorBuilder: (context, index) {
Function roundToDay = (DateTime date) =>
DateTime(date.year, date.month, date.day);
Search search = snapshot.data[index];
DateTime searchDate = roundToDay(search.timestamp);
bool newDate = true;
if (index != 0) {
Search prevSearch = snapshot.data[index - 1];
DateTime prevSearchDate = roundToDay(prevSearch.timestamp);
newDate = prevSearchDate != searchDate;
}
if (newDate) {
if (searchDate == roundToDay(DateTime.now()))
return DateDivider(text: "Today");
else if (searchDate ==
roundToDay(
DateTime.now().subtract(const Duration(days: 1))))
return DateDivider(text: "Yesterday");
return DateDivider(date: searchDate);
}
return Divider();
},
);
},
2021-07-17 16:11:17 +02:00
);
},
2020-07-09 22:17:10 +02:00
);
}
}