fix: resolve flutter analyze errors - remove leaked code, fix method calls, cleanup imports

This commit is contained in:
2026-03-23 16:55:54 +07:00
parent 4f202936fa
commit 71f1feaf98
33 changed files with 2851 additions and 224 deletions
@@ -1,72 +1,265 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../app/router/route_names.dart';
import '../../../core/models/chapter_model.dart';
import '../providers/reader_provider.dart';
import 'tts_player_widget.dart';
class ReaderScreen extends StatefulWidget {
class ReaderScreen extends ConsumerStatefulWidget {
const ReaderScreen({super.key, required this.chapterId});
final String chapterId;
@override
State<ReaderScreen> createState() => _ReaderScreenState();
ConsumerState<ReaderScreen> createState() => _ReaderScreenState();
}
class _ReaderScreenState extends State<ReaderScreen> {
double fontSize = 18;
class _ReaderScreenState extends ConsumerState<ReaderScreen> {
final ScrollController _scrollCtrl = ScrollController();
bool _showUI = true;
@override
void initState() {
super.initState();
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollCtrl.addListener(_onScroll);
});
}
@override
void dispose() {
_scrollCtrl.removeListener(_onScroll);
_scrollCtrl.dispose();
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
super.dispose();
}
void _onScroll() {
ref.read(readerProvider.notifier).updateScroll(_scrollCtrl.offset);
}
void _toggleUI() => setState(() => _showUI = !_showUI);
@override
Widget build(BuildContext context) {
final chapterAsync = ref.watch(chapterProvider(widget.chapterId));
final settings = ref.watch(readingSettingsProvider);
return Scaffold(
appBar: AppBar(
title: Text('Doc chuong ${widget.chapterId.isEmpty ? '?' : widget.chapterId}'),
actions: [
IconButton(
onPressed: () => context.push(RouteNames.settings),
icon: const Icon(Icons.tune),
tooltip: 'Cai dat doc',
body: chapterAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.error_outline, size: 48),
const SizedBox(height: 8),
Text('Lỗi tải chương: $e'),
FilledButton(
onPressed: () => ref.invalidate(chapterProvider(widget.chapterId)),
child: const Text('Thử lại'),
),
],
),
],
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Reader body placeholder with TOC, TTS, offline marker.'),
const SizedBox(height: 12),
Text('Co chu hien tai: ${fontSize.toStringAsFixed(0)}'),
Slider(
min: 14,
max: 26,
value: fontSize,
onChanged: (v) => setState(() => fontSize = v),
),
const Spacer(),
Row(
),
data: (chapter) {
// Initialize progress tracking
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(readerProvider.notifier).open(
chapter.novelId,
chapter.id,
chapter.number,
);
});
return GestureDetector(
onTap: _toggleUI,
child: Stack(
children: [
Expanded(
child: OutlinedButton(
onPressed: () {},
child: const Text('Chuong truoc'),
// Main content
Scrollbar(
controller: _scrollCtrl,
child: SingleChildScrollView(
controller: _scrollCtrl,
padding: const EdgeInsets.fromLTRB(20, 80, 20, 80),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Chương ${chapter.number}: ${chapter.title}',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 20),
SelectableText(
chapter.content,
style: TextStyle(
fontSize: settings.fontSize,
height: settings.lineHeight,
letterSpacing: settings.letterSpacing,
fontFamily: settings.fontFamily == 'serif' ? 'Georgia' : null,
),
),
const SizedBox(height: 40),
_NavButtons(chapter: chapter),
const SizedBox(height: 32),
],
),
),
),
const SizedBox(width: 12),
Expanded(
child: FilledButton(
onPressed: () {},
child: const Text('Chuong sau'),
// Floating top bar
AnimatedSlide(
offset: _showUI ? Offset.zero : const Offset(0, -1),
duration: const Duration(milliseconds: 200),
child: _TopBar(chapter: chapter),
),
// Floating bottom bar with font controls
AnimatedSlide(
offset: _showUI ? Offset.zero : const Offset(0, 1),
duration: const Duration(milliseconds: 200),
child: Align(
alignment: Alignment.bottomCenter,
child: _BottomBar(settings: settings, onSettingsChanged: (s) {
ref.read(readingSettingsProvider.notifier).update(s);
}),
),
),
],
),
],
),
),
floatingActionButton: FloatingActionButton.small(
onPressed: () {},
child: const Icon(Icons.record_voice_over),
);
},
),
);
}
}
class _TopBar extends StatelessWidget {
final ChapterModel chapter;
const _TopBar({required this.chapter});
@override
Widget build(BuildContext context) {
return Container(
color: Theme.of(context).colorScheme.surface.withAlpha(230),
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
child: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
title: Text(
chapter.volumeTitle ?? 'Chương ${chapter.number}',
style: Theme.of(context).textTheme.bodyMedium,
),
leading: BackButton(onPressed: () => Navigator.maybePop(context)),
actions: [
IconButton(
icon: const Icon(Icons.comment_outlined),
onPressed: () => context.push(
RouteNames.commentsFor(chapter.novelId, chapterId: chapter.id),
),
),
IconButton(
icon: const Icon(Icons.record_voice_over_outlined),
onPressed: () => showModalBottomSheet(
context: context,
builder: (_) => Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Text-to-Speech',
style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 16),
TtsPlayerWidget(content: chapter.content),
],
),
),
),
),
],
),
);
}
}
class _BottomBar extends StatelessWidget {
final dynamic settings;
final void Function(dynamic) onSettingsChanged;
const _BottomBar({required this.settings, required this.onSettingsChanged});
@override
Widget build(BuildContext context) {
return Container(
color: Theme.of(context).colorScheme.surface.withAlpha(230),
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).padding.bottom + 8,
left: 16,
right: 16,
top: 8,
),
child: Row(
children: [
const Icon(Icons.text_decrease, size: 18),
Expanded(
child: Slider(
value: settings.fontSize,
min: 12,
max: 28,
divisions: 8,
onChanged: (v) => onSettingsChanged(settings.copyWith(fontSize: v)),
),
),
const Icon(Icons.text_increase, size: 18),
const SizedBox(width: 8),
IconButton(
icon: const Icon(Icons.format_line_spacing),
onPressed: () {
final next = settings.lineHeight < 2.4
? settings.lineHeight + 0.2
: 1.4;
onSettingsChanged(settings.copyWith(lineHeight: next));
},
),
],
),
);
}
}
class _NavButtons extends ConsumerWidget {
final ChapterModel chapter;
const _NavButtons({required this.chapter});
@override
Widget build(BuildContext context, WidgetRef ref) {
return Row(
children: [
if (chapter.prevChapterId != null)
Expanded(
child: OutlinedButton.icon(
onPressed: () => context.pushReplacement(
RouteNames.readerChapter(chapter.prevChapterId!),
),
icon: const Icon(Icons.chevron_left),
label: Text('Ch. ${chapter.prevChapterNumber ?? '?'}'),
),
),
if (chapter.prevChapterId != null && chapter.nextChapterId != null)
const SizedBox(width: 12),
if (chapter.nextChapterId != null)
Expanded(
child: FilledButton.icon(
onPressed: () => context.pushReplacement(
RouteNames.readerChapter(chapter.nextChapterId!),
),
icon: const Icon(Icons.chevron_right),
label: Text('Ch. ${chapter.nextChapterNumber ?? '?'}'),
),
),
],
);
}
}
@@ -0,0 +1,75 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../tts/tts_service.dart';
class TtsPlayerWidget extends ConsumerWidget {
final String content;
const TtsPlayerWidget({super.key, required this.content});
@override
Widget build(BuildContext context, WidgetRef ref) {
final tts = ref.watch(ttsProvider);
final notifier = ref.read(ttsProvider.notifier);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.secondaryContainer,
borderRadius: BorderRadius.circular(24),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.skip_previous),
onPressed: tts.status != TtsStatus.idle ? notifier.skipBack : null,
),
// Play/Pause/Stop
if (!tts.isPlaying)
IconButton.filled(
icon: const Icon(Icons.play_arrow),
onPressed: () => notifier.startReading(
content,
paragraphIndex: tts.paragraphIndex,
),
)
else
IconButton.filled(
icon: const Icon(Icons.pause),
onPressed: notifier.pause,
),
IconButton(
icon: const Icon(Icons.stop),
onPressed: tts.status != TtsStatus.idle ? notifier.stop : null,
),
IconButton(
icon: const Icon(Icons.skip_next),
onPressed: tts.status != TtsStatus.idle ? notifier.skipForward : null,
),
// Speed control
PopupMenuButton<double>(
initialValue: tts.speed,
onSelected: notifier.setSpeed,
icon: Text(
'${tts.speed}x',
style: Theme.of(context).textTheme.labelSmall,
),
itemBuilder: (_) => [0.5, 0.75, 1.0, 1.25, 1.5, 2.0]
.map((s) => PopupMenuItem(value: s, child: Text('${s}x')))
.toList(),
),
// Progress indicator
if (tts.totalParagraphs > 0)
Padding(
padding: const EdgeInsets.only(right: 8),
child: Text(
'${tts.paragraphIndex + 1}/${tts.totalParagraphs}',
style: Theme.of(context).textTheme.labelSmall,
),
),
],
),
);
}
}
@@ -0,0 +1,130 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/models/chapter_model.dart';
import '../../../core/models/reading_settings.dart';
import '../../../core/network/providers.dart';
import '../../../core/storage/local_store.dart';
import '../../../core/storage/offline_cache.dart';
// ─── Chapter content ─────────────────────────────────────────────────────────
final chapterProvider =
FutureProvider.family<ChapterModel, String>((ref, chapterId) async {
final offlineCache = ref.read(offlineCacheProvider);
// Try network first, fall back to cache
try {
final client = ref.read(apiClientProvider);
final res = await client.dio.get('/api/chapters/$chapterId');
final chapter = ChapterModel.fromJson(res.data as Map<String, dynamic>);
// Cache for offline use (fire and forget)
unawaited(offlineCache.saveChapter(chapter));
return chapter;
} catch (_) {
final cached = await offlineCache.loadChapter(chapterId);
if (cached != null) return cached;
rethrow;
}
});
// ─── Reading progress ─────────────────────────────────────────────────────────
class ReadingProgress {
final String novelId;
final String chapterId;
final int chapterNumber;
final double scrollOffset;
const ReadingProgress({
required this.novelId,
required this.chapterId,
required this.chapterNumber,
required this.scrollOffset,
});
}
class ReaderNotifier extends StateNotifier<ReadingProgress?> {
final Ref _ref;
String? _novelId;
ReaderNotifier(this._ref) : super(null);
void open(String novelId, String chapterId, int chapterNumber) {
_novelId = novelId;
state = ReadingProgress(
novelId: novelId,
chapterId: chapterId,
chapterNumber: chapterNumber,
scrollOffset: 0,
);
_persistProgress(chapterId, chapterNumber, 0);
}
void updateScroll(double offset) {
if (state == null) return;
state = ReadingProgress(
novelId: state!.novelId,
chapterId: state!.chapterId,
chapterNumber: state!.chapterNumber,
scrollOffset: offset,
);
_debounceUpdate(offset);
}
Future<void> _persistProgress(
String chapterId, int chapterNumber, double offset) async {
final localStore = _ref.read(localStoreProvider);
await localStore.saveProgress(_novelId!, chapterId, chapterNumber, offset);
// Also notify server (fire and forget)
try {
final client = _ref.read(apiClientProvider);
await client.dio.post('/api/user/reading-progress', data: {
'novelId': _novelId,
'chapterId': chapterId,
'chapterNumber': chapterNumber,
'progress': offset,
});
} catch (_) {}
}
DateTime? _lastUpdate;
Future<void> _debounceUpdate(double offset) async {
final now = DateTime.now();
if (_lastUpdate != null && now.difference(_lastUpdate!).inSeconds < 3) return;
_lastUpdate = now;
if (state != null) {
await _persistProgress(state!.chapterId, state!.chapterNumber, offset);
}
}
}
final readerProvider =
StateNotifierProvider<ReaderNotifier, ReadingProgress?>((ref) {
return ReaderNotifier(ref);
});
// ─── Reading settings ─────────────────────────────────────────────────────────
class ReadingSettingsNotifier extends StateNotifier<ReadingSettings> {
final Ref _ref;
ReadingSettingsNotifier(this._ref) : super(const ReadingSettings()) {
_load();
}
Future<void> _load() async {
final localStore = _ref.read(localStoreProvider);
final saved = await localStore.loadReadingSettings();
if (saved != null) state = saved;
}
Future<void> update(ReadingSettings settings) async {
state = settings;
final localStore = _ref.read(localStoreProvider);
await localStore.saveReadingSettings(settings);
}
}
final readingSettingsProvider =
StateNotifierProvider<ReadingSettingsNotifier, ReadingSettings>((ref) {
return ReadingSettingsNotifier(ref);
});
+149
View File
@@ -0,0 +1,149 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:wakelock_plus/wakelock_plus.dart';
enum TtsStatus { idle, playing, paused }
class TtsState {
final TtsStatus status;
final int paragraphIndex;
final int totalParagraphs;
final double speed;
const TtsState({
this.status = TtsStatus.idle,
this.paragraphIndex = 0,
this.totalParagraphs = 0,
this.speed = 1.0,
});
TtsState copyWith({
TtsStatus? status,
int? paragraphIndex,
int? totalParagraphs,
double? speed,
}) =>
TtsState(
status: status ?? this.status,
paragraphIndex: paragraphIndex ?? this.paragraphIndex,
totalParagraphs: totalParagraphs ?? this.totalParagraphs,
speed: speed ?? this.speed,
);
bool get isPlaying => status == TtsStatus.playing;
}
class TtsNotifier extends StateNotifier<TtsState> {
final FlutterTts _tts = FlutterTts();
List<String> _paragraphs = [];
TtsNotifier() : super(const TtsState()) {
_init();
}
Future<void> _init() async {
await _tts.setLanguage('vi-VN');
await _tts.setSpeechRate(1.0);
await _tts.setVolume(1.0);
await _tts.setPitch(1.0);
_tts.setCompletionHandler(() {
if (state.status == TtsStatus.playing) {
_next();
}
});
_tts.setErrorHandler((msg) {
state = state.copyWith(status: TtsStatus.idle);
WakelockPlus.disable();
});
}
/// Start reading from [content] starting at optional [paragraphIndex].
Future<void> startReading(String content, {int paragraphIndex = 0}) async {
_paragraphs = content
.split(RegExp(r'\n+'))
.map((p) => p.trim())
.where((p) => p.isNotEmpty)
.toList();
if (_paragraphs.isEmpty) return;
final validIndex = paragraphIndex.clamp(0, _paragraphs.length - 1);
state = state.copyWith(
status: TtsStatus.playing,
paragraphIndex: validIndex,
totalParagraphs: _paragraphs.length,
);
await WakelockPlus.enable();
await _speak(validIndex);
}
Future<void> _speak(int index) async {
if (index >= _paragraphs.length) {
state = state.copyWith(status: TtsStatus.idle);
await WakelockPlus.disable();
return;
}
await _tts.setSpeechRate(state.speed);
await _tts.speak(_paragraphs[index]);
}
Future<void> _next() async {
final next = state.paragraphIndex + 1;
if (next >= state.totalParagraphs) {
state = state.copyWith(status: TtsStatus.idle, paragraphIndex: 0);
await WakelockPlus.disable();
return;
}
state = state.copyWith(paragraphIndex: next);
await _speak(next);
}
Future<void> pause() async {
await _tts.pause();
state = state.copyWith(status: TtsStatus.paused);
await WakelockPlus.disable();
}
Future<void> resume() async {
if (state.status != TtsStatus.paused) return;
state = state.copyWith(status: TtsStatus.playing);
await WakelockPlus.enable();
await _speak(state.paragraphIndex);
}
Future<void> stop() async {
await _tts.stop();
state = state.copyWith(status: TtsStatus.idle, paragraphIndex: 0);
await WakelockPlus.disable();
}
Future<void> skipForward() async {
await _tts.stop();
await _next();
}
Future<void> skipBack() async {
await _tts.stop();
final prev = (state.paragraphIndex - 1).clamp(0, state.totalParagraphs - 1);
state = state.copyWith(paragraphIndex: prev);
if (state.status == TtsStatus.playing) await _speak(prev);
}
Future<void> setSpeed(double speed) async {
state = state.copyWith(speed: speed);
await _tts.setSpeechRate(speed);
}
@override
void dispose() {
_tts.stop();
WakelockPlus.disable();
super.dispose();
}
}
final ttsProvider = StateNotifierProvider<TtsNotifier, TtsState>((ref) {
return TtsNotifier();
});