-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsimulation_exam_page.dart
More file actions
executable file
·801 lines (737 loc) · 29 KB
/
Copy pathsimulation_exam_page.dart
File metadata and controls
executable file
·801 lines (737 loc) · 29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:cap_countdown/main.dart';
import 'package:cap_countdown/src/exam/cap_subject.dart';
import 'package:cap_countdown/src/exam/exam_subject.dart';
import 'package:cap_countdown/src/exam/group_choice_question.dart';
import 'package:cap_countdown/src/exam/question_meta.dart';
import 'package:cap_countdown/src/exam/question_record.dart';
import 'package:cap_countdown/src/exam/single_choice_question.dart';
import 'package:cap_countdown/src/exam/subject_question.dart';
import 'package:cap_countdown/src/widgets/optional_question_view.dart';
import 'package:cap_countdown/src/widgets/question_text.dart';
import 'package:cap_countdown/src/widgets/subject_question_view.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
class SimulationExamPage extends StatefulWidget {
final int year;
final String examName;
final ExamSubject subject;
const SimulationExamPage(
{Key? key,
required this.year,
required this.examName,
required this.subject})
: super(key: key);
@override
State<SimulationExamPage> createState() => _SimulationExamPageState();
}
class _SimulationExamPageState extends State<SimulationExamPage> {
final _pageController = PageController();
int _currentPage = 0;
bool _submitted = false;
late bool _disablePageChange;
late List<bool> _submittedList;
final Stopwatch _stopwatch = Stopwatch();
@override
void initState() {
_disablePageChange =
widget.subject.subjectId == CAPSubject.englishListening;
_submittedList = List.filled(widget.subject.questions.length, false);
_stopwatch.start();
super.initState();
}
@override
Widget build(BuildContext context) {
final questions = widget.subject.questions;
final question = questions[_currentPage];
final isFavorite =
localStorage.questionRecords[question.hash]?.isFavorite ?? false;
final tookNote = localStorage.questionRecords[question.hash]?.note != null;
String getUsedTimeString() {
String toReturn = "用時:";
final hours = _stopwatch.elapsed.inHours % 24;
final minutes = _stopwatch.elapsed.inMinutes % 60;
final seconds = _stopwatch.elapsed.inSeconds % 60;
if (hours > 0) {
toReturn += "${hours.toString()}時";
}
if (minutes > 0) {
toReturn += "${minutes.toString()}分";
}
toReturn += "${seconds.toString()}秒";
return toReturn;
}
return WillPopScope(
onWillPop: () async {
// Prevent using system navigation to leave this page.
_showBackDialog();
return false;
},
child: Scaffold(
appBar: AppBar(
title: Text(widget.examName, style: const TextStyle(fontSize: 18)),
actions: [
IconButton(
onPressed: () {
_showNoteDialog(question);
},
icon: tookNote
? Icon(Icons.draw_rounded,
color: Theme.of(context).colorScheme.primary)
: const Icon(Icons.draw_outlined),
tooltip: '做筆記'),
IconButton(
onPressed: () {
if (isFavorite) {
question.removeFromFavorite();
} else {
question.addToFavorite();
}
setState(() {});
},
icon: isFavorite
? const Icon(Icons.favorite, color: Colors.red)
: const Icon(Icons.favorite_border),
tooltip: isFavorite ? '取消收藏' : '加入收藏'),
],
leading: BackButton(
onPressed: () {
_showBackDialog();
},
),
),
body: Column(
children: [
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
if (!(_submitted || !localStorage.simulationExamTiming))
ExamTimer(
duration: widget.subject.duration,
onExamOver: () {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: const Text('警告'),
content: const Text('考試時間已到,請勿繼續作答!'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
_submit();
},
child: const Text('確定'))
],
);
});
},
),
if (widget.subject.subjectId == CAPSubject.math) ...[
if (!_submitted)
const SizedBox(
width: 20,
),
const MathReferenceFormula()
]
]),
if (_submitted) ...[
GradeMarkings(subject: widget.subject),
Text(
getUsedTimeString(),
style: const TextStyle(fontSize: 20),
),
],
const Divider(),
Expanded(
child: PageView.builder(
controller: _pageController,
itemCount: questions.length,
physics: _disablePageChange
? const NeverScrollableScrollPhysics()
: null,
itemBuilder: (context, index) {
final question = questions[index];
return _QuestionPage(
question: question,
meta: QuestionMeta(
year: widget.year,
subjectId: widget.subject.subjectId,
questionIndex: index,
questionNumber: question.questionNumber),
option: QuestionViewOption(
showQuestionNumber: true,
submitted: (_submitted || _submittedList[index]),
onlyPlayAudioOnce:
!(_submitted || _submittedList[index]),
onAudioPlayStateChanged: (state) {
setState(() {
_disablePageChange = state == PlayerState.playing;
});
}),
onQuestionSubmitted: (value) {
setState(() {
_submittedList[index] = value;
});
},
);
},
onPageChanged: (page) {
setState(() {
_currentPage = page;
});
},
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
if (!_submitted && _currentPage == questions.length - 1)
_buildSubmitButton(),
Row(
children: [
Expanded(
child: ElevatedButton(
onPressed: () {
if (_disablePageChange) return;
_pageController.previousPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut);
},
style: ElevatedButton.styleFrom(
foregroundColor:
_disablePageChange || _currentPage == 0
? Theme.of(context).disabledColor
: null),
child: const Text('上一題'),
),
),
const SizedBox(width: 8),
QuestionNumberIndicator(
currentPage: _currentPage,
subject: widget.subject,
enable: !_disablePageChange,
onPageChanged: (page) {
final isEnglishListening =
widget.subject.subjectId ==
CAPSubject.englishListening;
// When the exam subject is English listening, disable the animation page change.
// Because if there is animation, the audio will be played when passing through each page.
if (isEnglishListening) {
_pageController.jumpToPage(page);
return;
}
_pageController.animateToPage(page,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut);
},
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton(
onPressed: () {
if (_disablePageChange) return;
if (_currentPage == questions.length - 1) return;
_pageController.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut);
},
style: ElevatedButton.styleFrom(
foregroundColor: _disablePageChange
? Theme.of(context).disabledColor
: null),
child: const Text('下一題'),
),
),
],
),
],
),
),
],
)),
);
}
FloatingActionButton _buildSubmitButton() {
return FloatingActionButton.extended(
onPressed: () {
final optionalQuestions = widget.subject.getOptionalQuestions();
if (optionalQuestions.any((q) => q.selectedChoice == null)) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('確認交卷'),
content:
const Text('您尚有未作答的題目,您仍然要交卷嗎?\n還有一些時間,建議您可以繼續作答。'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('取消')),
TextButton(
onPressed: () {
Navigator.of(context).pop();
_submit();
},
child: const Text('確定'))
],
);
});
return;
}
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('確認交卷'),
content: const Text('您確定要交卷了嗎?\n還有一些時間,建議您可以先檢查看看再交卷。'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('取消')),
TextButton(
onPressed: () {
Navigator.of(context).pop();
_submit();
},
child: const Text('確定'))
],
);
});
},
icon: const Icon(Icons.done_rounded),
label: const Text('交卷'));
}
void _showBackDialog() {
if (_submitted) {
widget.subject.clearSelectRecords();
Navigator.of(context).popUntil((route) => route.isFirst);
return;
}
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('確定要離開嗎?'),
content: const Text('這將會清除本次的作答紀錄。'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('取消'),
),
TextButton(
onPressed: () {
widget.subject.clearSelectRecords();
Navigator.of(context).popUntil((route) => route.isFirst);
},
child: const Text('確定'),
),
],
);
});
}
void _submit() {
_stopwatch.stop();
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('智慧老師正在為您批改考卷...'),
content:
Lottie.asset('assets/animations/135507-exam-prep-topics.json',
onLoaded: (composition) async {
await Future.delayed(const Duration(milliseconds: 2800));
if (mounted) {
setState(() {
_submitted = true;
_submittedList = List.filled(_submittedList.length, true);
final optionalQuestions =
widget.subject.getOptionalQuestions();
for (final question in optionalQuestions) {
question.makeAsAnswered();
}
});
Navigator.of(context).pop();
}
}),
));
}
void _showNoteDialog(SubjectQuestion question) {
final records = localStorage.questionRecords;
QuestionRecord? record = records[question.hash] ?? const QuestionRecord();
final noteController = TextEditingController(text: record.note ?? '');
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('筆記'),
content: TextField(
controller: noteController,
maxLines: null,
decoration: const InputDecoration(
border: OutlineInputBorder(), hintText: '請輸入筆記'),
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('取消'),
),
TextButton(
onPressed: () {
final text = noteController.text;
records[question.hash] =
record.copyWith(note: text.isEmpty ? null : text);
localStorage.questionRecords = records;
Navigator.of(context).pop();
setState(() {});
},
child: const Text('確定'),
),
],
);
});
}
}
class _QuestionPage extends StatefulWidget {
const _QuestionPage(
{required this.question,
required this.meta,
required this.option,
required this.onQuestionSubmitted});
final SubjectQuestion question;
final QuestionMeta meta;
final QuestionViewOption option;
final ValueChanged<bool>? onQuestionSubmitted;
@override
State<_QuestionPage> createState() => _QuestionPageState();
}
class _QuestionPageState extends State<_QuestionPage>
with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context);
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: SubjectQuestionView(
question: widget.question,
meta: widget.meta,
option: widget.option,
actions: localStorage.simulationExamShowAnsBtn
? (questions) => [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
(!widget.option.submitted)
? FilledButton.icon(
onPressed: () {
final isSelectAll = questions
.every((q) => q.selectedChoice != null);
final messenger =
ScaffoldMessenger.of(context);
messenger.clearSnackBars();
if (!isSelectAll) {
messenger.showSnackBar(
const SnackBar(
content: Text('交卷前請先記得選擇答案喔!',
style: TextStyle(
fontWeight: FontWeight.bold)),
backgroundColor: Colors.orange,
),
);
return;
}
if (questions.every((q) => q.isCorrect)) {
messenger.showSnackBar(
SnackBar(
content: Text(questions.length > 1
? '恭喜你全都答對了!'
: '恭喜你答對了!'),
backgroundColor: Colors.green,
),
);
} else {
messenger.showSnackBar(
const SnackBar(
content: Text('答錯了,再接再厲!記得看詳解修正錯誤呦!'),
backgroundColor: Colors.red,
),
);
}
setState(() {
widget.onQuestionSubmitted?.call(true);
for (final q in questions) {
q.makeAsAnswered();
}
});
},
icon: const Icon(Icons.check),
label: const Text('對答案'))
: FilledButton.icon(
onPressed: () {
setState(() {
widget.onQuestionSubmitted?.call(false);
});
},
icon: const Icon(Icons.visibility_off_outlined),
label: const Text('隱藏答案'))
])
]
: null,
),
));
}
@override
bool get wantKeepAlive => true;
}
class QuestionNumberIndicator extends StatefulWidget {
final int currentPage;
final ExamSubject subject;
final bool enable;
final void Function(int page) onPageChanged;
const QuestionNumberIndicator(
{super.key,
required this.currentPage,
required this.subject,
required this.enable,
required this.onPageChanged});
@override
State<QuestionNumberIndicator> createState() =>
_QuestionNumberIndicatorState();
}
class _QuestionNumberIndicatorState extends State<QuestionNumberIndicator> {
late TextEditingController _textEditingController;
@override
void initState() {
super.initState();
_textEditingController = TextEditingController(text: _getQuestionNumber());
}
String _getQuestionNumber() {
final question = widget.subject.questions[widget.currentPage];
return question.questionNumber;
}
@override
void dispose() {
_textEditingController.dispose();
super.dispose();
}
@override
void didUpdateWidget(covariant QuestionNumberIndicator oldWidget) {
super.didUpdateWidget(oldWidget);
_textEditingController.text = _getQuestionNumber();
}
@override
Widget build(BuildContext context) {
final textStyle = Theme.of(context).textTheme.bodyLarge;
final optionalQuestions = widget.subject.getOptionalQuestions();
return Row(
children: [
SizedBox(
height: 45,
width: 55,
child: TextField(
controller: _textEditingController,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
enabled: widget.enable,
onSubmitted: (value) {
final inputPage =
(int.tryParse(value) ?? 1).clamp(1, optionalQuestions.length);
int page = widget.subject.questions.indexWhere((question) {
if (question is SingleChoiceQuestion) {
return question.number == inputPage;
} else if (question is GroupChoiceQuestion) {
return question.options.any((e) => e.number == inputPage);
} else {
return false;
}
});
widget.onPageChanged(page);
setState(() {
_textEditingController.text = _getQuestionNumber();
});
},
),
),
Text(' / ${optionalQuestions.length}', style: textStyle),
],
);
}
}
class ExamTimer extends StatefulWidget {
final Duration duration;
final void Function() onExamOver;
const ExamTimer({
super.key,
required this.duration,
required this.onExamOver,
});
@override
State<ExamTimer> createState() => _ExamTimerState();
}
class _ExamTimerState extends State<ExamTimer> {
late Timer _timer;
Duration _remainingTime = Duration.zero;
@override
void initState() {
super.initState();
_remainingTime = widget.duration;
_startTimer();
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
void _startTimer() {
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() {
_remainingTime = widget.duration - Duration(seconds: timer.tick);
if (_remainingTime <= Duration.zero) {
_timer.cancel();
widget.onExamOver();
}
});
});
}
@override
Widget build(BuildContext context) {
final hours = _remainingTime.inHours.remainder(24);
final minutes = _remainingTime.inMinutes.remainder(60);
final seconds = _remainingTime.inSeconds.remainder(60);
Color? textColor;
if (_remainingTime.inMinutes <= 5) {
textColor = Colors.red;
} else if (_remainingTime.inMinutes <= 10) {
textColor = Colors.orange;
} else if (_remainingTime.inMinutes <= 15) {
textColor = Colors.yellow;
}
return Text(
'${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}',
style:
Theme.of(context).textTheme.headlineLarge?.copyWith(color: textColor),
);
}
}
class GradeMarkings extends StatelessWidget {
final ExamSubject subject;
const GradeMarkings({Key? key, required this.subject}) : super(key: key);
Text _getGradeMarkingText(BuildContext context, int correctCount, int total) {
final chart = subject.gradeMarkings;
final String gradeMarking;
if (subject.subjectId == CAPSubject.math) {
final percentage = (correctCount / total) * 100;
gradeMarking = chart.entries
.firstWhere((entry) => percentage >= entry.value,
orElse: () => chart.entries.last)
.key;
} else {
gradeMarking = chart.entries
.firstWhere((entry) => correctCount >= entry.value,
orElse: () => chart.entries.last)
.key;
}
final Color color;
// https://cap.rcpet.edu.tw/score3.html
if (subject.subjectId == CAPSubject.englishListening &&
gradeMarking.contains('基礎')) {
color = Colors.green;
} else if (gradeMarking.contains('A') || gradeMarking.contains('精熟')) {
color = Colors.green;
} else if (gradeMarking.contains('B+') || gradeMarking.contains('基礎')) {
color = Colors.blue;
} else if (gradeMarking.contains('B')) {
color = Colors.orange;
} else if (gradeMarking.contains('C') || gradeMarking.contains('待加強')) {
color = Colors.red;
} else {
color = Colors.white;
}
return Text(gradeMarking,
style: Theme.of(context)
.textTheme
.displayMedium
?.copyWith(color: color, fontWeight: FontWeight.bold));
}
@override
Widget build(BuildContext context) {
final allQuestion = subject.getOptionalQuestions();
final correctCount = allQuestion.where((q) => q.isCorrect).length;
final textStyle = Theme.of(context).textTheme.bodyLarge;
return Column(
children: [
Text('等級加標示', style: textStyle),
_getGradeMarkingText(context, correctCount, allQuestion.length),
Text('答對題數($correctCount / ${allQuestion.length})', style: textStyle),
Text('記得看看詳解了解問題,加油!', style: textStyle),
],
);
}
}
class MathReferenceFormula extends StatelessWidget {
const MathReferenceFormula({super.key});
@override
Widget build(BuildContext context) {
return InkWell(
child: const Padding(
padding: EdgeInsets.all(5),
child: Column(
children: [Icon(Icons.list), Text("參考公式")],
)),
onTap: () {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (BuildContext context) {
return const Padding(
padding: EdgeInsets.all(20),
child: Wrap(runSpacing: 8, children: [
QuestionText(text: '參考公式:'),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("📖 "),
Column(children: [
QuestionText(
text:
"和的平方公式:\$(a+b)^2\$\$=a^2\$\$+2ab\$\$+b^2\$"),
QuestionText(
text:
"差的平方公式:\$(a-b)^2\$\$=a^2\$\$-2ab\$\$+b^2\$"),
QuestionText(
text: "平方差公式:\$a^2-b^2\$\$=(a+b)(a-b)\$"),
])
]),
QuestionText(
text:
"📖 若直角三角形兩股長為 \$a\$ 、 \$b\$,斜邊長為 \$c\$,則 \$c^2\$\$=a^2\$\$+b^2\$"),
QuestionText(
text:
"📖 若圓的半徑為 \$r\$,圓周率為 \$\\pi\$,則圓面積 \$=\\pi r^2\$,圓周長 \$=2 \\pi r\$"),
QuestionText(
text:
"📖 凸 n 邊形的內角和為 \$(n − 2)\$\$ \\times 180^\\circ\$ , \$n \\geq 3\$"),
QuestionText(
text:
"📖 若一個等差數列的首項為 \$a_1\$,公差為 \$d\$,第 \$n\$ 項為 \$a_n\$,前 \$n\$ 項和為 \$S_n\$,則 \$a_n\$\$ = a_1 \$\$+ (n − 1) d\$,\$S_n\$\$ =\\frac{n (a_1 + a_n)}{2}\$"),
QuestionText(
text:
"📖 若一個等比數列的首項為 \$a_1\$,公比為 \$r\$,第 \$n\$ 項為 \$a_n\$,則 \$a_n\$ \$= a_1r^{n − 1}\$"),
QuestionText(
text:
"📖 一元二次方程式 \$ax^2 \$\$+ bx \$\$+ c \$\$= 0\$ 的解為 \$x \$\$=\\frac{ −b\\pm \\sqrt{b^2 − 4ac}}{2a}\$")
]),
);
});
});
}
}