示例工程 ch14-persistence

ch14-persistence/lib/src/todos_page.dart

dart · 5.1 KB

// 待办页:drift 的 StreamProvider + Riverpod 操作 + shared_preferences 设置。
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
 
import 'database.dart';
import 'providers.dart';
 
class TodosPage extends ConsumerStatefulWidget {
  const TodosPage({super.key});
 
  @override
  ConsumerState<TodosPage> createState() => _TodosPageState();
}
 
class _TodosPageState extends ConsumerState<TodosPage> {
  final TextEditingController _input = TextEditingController();
 
  @override
  void dispose() {
    _input.dispose();
    super.dispose();
  }
 
  Future<void> _add() async {
    final String text = _input.text;
    if (text.trim().isEmpty) return;
    await ref.read(todoActionsProvider).add(text);
    _input.clear();
  }
 
  @override
  Widget build(BuildContext context) {
    final AsyncValue<List<Todo>> todos = ref.watch(todosProvider);
    final int done = ref.watch(doneCountProvider);
    final String? lastSync = ref.watch(settingsProvider).lastSyncAt?.toLocal().toString();
 
    return Scaffold(
      appBar: AppBar(
        title: const Text('本地持久化'),
        actions: [
          IconButton(
            key: const Key('mark-sync'),
            tooltip: '记录同步时间(SharedPreferences)',
            onPressed: () async {
              // 先把 messenger 拿出来:await 之后再用 context 会被 lint(和实际生命周期)拦
              final ScaffoldMessengerState messenger = ScaffoldMessenger.of(context);
              await ref.read(todoActionsProvider).markSynced();
              if (!mounted) return;
              setState(() {}); // 重新读一次 SharedPreferences(它不是可监听的)
              messenger.showSnackBar(const SnackBar(content: Text('已记录同步时间')));
            },
            icon: const Icon(Icons.cloud_done_outlined),
          ),
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(12),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    key: const Key('todo-input'),
                    controller: _input,
                    decoration: const InputDecoration(
                      labelText: '新的待办',
                      border: OutlineInputBorder(),
                      isDense: true,
                    ),
                    onSubmitted: (_) => _add(),
                  ),
                ),
                const SizedBox(width: 8),
                FilledButton(key: const Key('todo-add'), onPressed: _add, child: const Text('添加')),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12),
            child: Row(
              children: [
                Text('已完成 $done 项', key: const Key('done-count')),
                const Spacer(),
                TextButton(
                  key: const Key('clear-done'),
                  onPressed: () => ref.read(todoActionsProvider).clearDone(),
                  child: const Text('清除已完成'),
                ),
              ],
            ),
          ),
          Expanded(
            child: todos.when(
              loading: () => const Center(child: CircularProgressIndicator(key: Key('todos-loading'))),
              error: (Object e, StackTrace _) => Center(
                child: Text('读取失败: $e', key: const Key('todos-error')),
              ),
              data: (List<Todo> items) {
                if (items.isEmpty) {
                  return const Center(child: Text('还没有待办', key: Key('todos-empty')));
                }
                return ListView.builder(
                  key: const Key('todo-list'),
                  itemCount: items.length,
                  itemBuilder: (BuildContext context, int index) {
                    final Todo todo = items[index];
                    return CheckboxListTile(
                      key: Key('todo-${todo.id}'),
                      value: todo.done,
                      title: Text(
                        todo.title,
                        style: todo.done ? const TextStyle(decoration: TextDecoration.lineThrough) : null,
                      ),
                      subtitle: Text('${todo.createdAt.toLocal()}'),
                      onChanged: (_) => ref.read(todoActionsProvider).toggle(todo),
                      secondary: IconButton(
                        key: Key('delete-${todo.id}'),
                        icon: const Icon(Icons.delete_outline),
                        onPressed: () => ref.read(todoActionsProvider).remove(todo),
                      ),
                    );
                  },
                );
              },
            ),
          ),
          const Divider(height: 1),
          Padding(
            padding: const EdgeInsets.all(12),
            child: Text(
              lastSync == null ? '上次同步:从未' : '上次同步:$lastSync',
              key: const Key('last-sync'),
              style: Theme.of(context).textTheme.bodySmall,
            ),
          ),
        ],
      ),
    );
  }
}