feat:增加提醒事项

This commit is contained in:
2025-11-08 22:06:16 +08:00
parent 27f0638c01
commit d5ff4c9b02
30 changed files with 1490 additions and 199 deletions

View File

@@ -6,6 +6,35 @@ import '../provider/app_provider.dart';
class AppDrawer extends StatelessWidget {
const AppDrawer({super.key});
DrawerHeader buildDrawerHeader() {
return DrawerHeader(
decoration: BoxDecoration(color: Colors.blue.shade700),
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CircleAvatar(
radius: 30,
backgroundColor: Colors.white,
child: Icon(Icons.flash_on, color: Colors.blue, size: 40),
),
SizedBox(height: 10),
Text(
'闪灵',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
Text(
'记录每一刻的灵感',
style: TextStyle(color: Colors.white70, fontSize: 14),
),
],
),
);
}
@override
Widget build(BuildContext context) {
return Drawer(
@@ -13,41 +42,7 @@ class AppDrawer extends StatelessWidget {
padding: EdgeInsets.zero,
children: [
// 抽屉头部
DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue.shade700,
),
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CircleAvatar(
radius: 30,
backgroundColor: Colors.white,
child: Icon(
Icons.flash_on,
color: Colors.blue,
size: 40,
),
),
SizedBox(height: 10),
Text(
'闪灵',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
Text(
'记录每一刻的灵感',
style: TextStyle(
color: Colors.white70,
fontSize: 14,
),
),
],
),
),
buildDrawerHeader(),
// 菜单项
_buildDrawerItem(
@@ -58,20 +53,12 @@ class AppDrawer extends StatelessWidget {
Provider.of<AppProvider>(context, listen: false).changeTab(0);
},
),
_buildDrawerItem(
icon: Icons.note,
title: '笔记',
onTap: () {
Navigator.pop(context);
Provider.of<AppProvider>(context, listen: false).changeTab(1);
},
),
_buildDrawerItem(
icon: Icons.checklist,
title: '待办事项',
onTap: () {
Navigator.pop(context);
Provider.of<AppProvider>(context, listen: false).changeTab(2);
Provider.of<AppProvider>(context, listen: false).changeTab(1);
},
),
_buildDrawerItem(
@@ -79,7 +66,7 @@ class AppDrawer extends StatelessWidget {
title: '提醒任务',
onTap: () {
Navigator.pop(context);
Provider.of<AppProvider>(context, listen: false).changeTab(3);
Provider.of<AppProvider>(context, listen: false).changeTab(2);
},
),
@@ -137,4 +124,4 @@ class AppDrawer extends StatelessWidget {
onTap: onTap,
);
}
}
}

View File

@@ -1,6 +1,5 @@
import 'package:flisp_app/layout/app_drawer.dart';
import 'package:flisp_app/pages/flash_page.dart';
import 'package:flisp_app/pages/notes_Page.dart';
import 'package:flisp_app/pages/reminders_page.dart';
import 'package:flisp_app/pages/todo_page.dart';
import 'package:flisp_app/provider/app_provider.dart';
@@ -16,10 +15,10 @@ class MainScreen extends StatefulWidget {
class _MainScreenState extends State<MainScreen> {
final GlobalKey<TodoPageState> _todoPageKey = GlobalKey();
final GlobalKey<ReminderPageState> _reminderPageKey = GlobalKey();
List<BottomNavigationBarItem> navItems = [
BottomNavigationBarItem(icon: Icon(Icons.flash_on), label: '闪灵'),
BottomNavigationBarItem(icon: Icon(Icons.note), label: '笔记'),
BottomNavigationBarItem(icon: Icon(Icons.checklist), label: '待办'),
BottomNavigationBarItem(icon: Icon(Icons.notifications), label: '提醒'),
];
@@ -51,9 +50,14 @@ class _MainScreenState extends State<MainScreen> {
}
void _onPressFloatingButton(int index) {
if (index == 2) {
print(index);
if (index == 1) {
if (_todoPageKey.currentState != null) {
_todoPageKey.currentState!.showAddTodoDialog();
_todoPageKey.currentState!.showAddDialog();
}
} else if (index == 2) {
if (_reminderPageKey.currentState != null) {
_reminderPageKey.currentState!.showAddDialog();
}
}
}
@@ -92,18 +96,16 @@ class _MainScreenState extends State<MainScreen> {
case 0:
return const FlashPage();
case 1:
return const NotesPage();
return TodoPage(key: _todoPageKey);
case 2:
return TodoPage(key: _todoPageKey); // 传递 key
case 3:
return const RemindersPage();
return RemindersPage(key: _reminderPageKey);
default:
return const FlashPage();
}
}
String _getAppBarTitle(int index) {
final titles = {0: '闪灵', 1: '笔记', 2: '待办', 3: '提醒'};
final titles = {0: '闪灵', 1: '待办', 2: '提醒'};
return titles[index] ?? '闪灵';
}
}

View File

@@ -1,8 +1,11 @@
import 'package:flisp_app/models/reminder.dart';
import 'package:flisp_app/provider/app_provider.dart';
import 'package:flisp_app/provider/reminder_provider.dart';
import 'package:flisp_app/utils/notify_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_quill/flutter_quill.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'layout/main_screen.dart';
@@ -11,16 +14,25 @@ import 'provider/todo_provider.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
// 初始化提醒服务
final notifyService = NotifyService();
await notifyService.initialize();
// 初始化Hive
await Hive.initFlutter();
// 注册适配器
Hive.registerAdapter(TodoAdapter());
Hive.registerAdapter(ReminderAdapter());
// 打开Box
final todosBox = await Hive.openBox<Todo>('todos');
// todosBox.clear();
todosBox.clear();
final remindersBox = await Hive.openBox<Reminder>('reminders');
// remindersBox.clear();
// notifyService.cancelAllNotifications();
runApp(const MyApp());
}
@@ -33,7 +45,8 @@ class MyApp extends StatelessWidget {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => AppProvider()),
ChangeNotifierProvider(create: (_) => TodoProvider()), // 新增
ChangeNotifierProvider(create: (_) => TodoProvider()),
ChangeNotifierProvider(create: (_) => ReminderProvider()),
],
child: MaterialApp(
title: '闪灵',
@@ -41,6 +54,7 @@ class MyApp extends StatelessWidget {
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
FlutterQuillLocalizations.delegate,
],
supportedLocales: [
const Locale('zh'),

58
lib/models/reminder.dart Normal file
View File

@@ -0,0 +1,58 @@
import 'package:hive/hive.dart';
// flutter packages pub run build_runner build
part 'reminder.g.dart';
@HiveType(typeId: 1)
class Reminder extends HiveObject {
@HiveField(0)
late int id;
@HiveField(1)
late String title;
@HiveField(2)
late String content;
@HiveField(3)
late DateTime scheduledTime;
@HiveField(4)
late DateTime createTime;
@HiveField(5)
late DateTime updateTime;
Reminder({
int? id,
required this.title,
required this.content,
required this.scheduledTime,
DateTime? createTime,
DateTime? updateTime,
}) {
// 简单时间戳ID
this.id = id ?? DateTime.now().millisecondsSinceEpoch ~/ 1000;
this.createTime = createTime ?? DateTime.now();
this.updateTime = updateTime ?? DateTime.now();
}
Reminder copyWith({String? title, String? content, DateTime? scheduledTime}) {
return Reminder(
id: id,
title: title ?? this.title,
content: content ?? this.content,
scheduledTime: scheduledTime ?? this.scheduledTime,
createTime: createTime,
updateTime: DateTime.now(),
);
}
static Reminder getEmpty() {
return Reminder(
id: DateTime.now().millisecondsSinceEpoch ~/ 1000,
title: '日常提醒',
content: '',
scheduledTime: DateTime.now().add(Duration(minutes: 5)),
);
}
}

View File

@@ -0,0 +1,56 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'reminder.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class ReminderAdapter extends TypeAdapter<Reminder> {
@override
final int typeId = 1;
@override
Reminder read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Reminder(
id: fields[0] as int?,
title: fields[1] as String,
content: fields[2] as String,
scheduledTime: fields[3] as DateTime,
createTime: fields[4] as DateTime?,
updateTime: fields[5] as DateTime?,
);
}
@override
void write(BinaryWriter writer, Reminder obj) {
writer
..writeByte(6)
..writeByte(0)
..write(obj.id)
..writeByte(1)
..write(obj.title)
..writeByte(2)
..write(obj.content)
..writeByte(3)
..write(obj.scheduledTime)
..writeByte(4)
..write(obj.createTime)
..writeByte(5)
..write(obj.updateTime);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ReminderAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}

View File

@@ -30,6 +30,7 @@ class Todo extends HiveObject {
late DateTime updateTime;
TodoPriority get priority => TodoPriority.values[priorityIndex];
set priority(TodoPriority value) => priorityIndex = value.index;
Todo({
@@ -43,7 +44,7 @@ class Todo extends HiveObject {
DateTime? updateTime,
}) {
// 简单时间戳ID
this.id = id ?? DateTime.now().millisecondsSinceEpoch;
this.id = id ?? DateTime.now().millisecondsSinceEpoch ~/ 1000;
this.priorityIndex = priority.index;
this.createTime = createTime ?? DateTime.now();
this.updateTime = updateTime ?? DateTime.now();
@@ -70,8 +71,8 @@ class Todo extends HiveObject {
static Todo getEmpty() {
return Todo(
id: DateTime.now().millisecondsSinceEpoch,
title: '',
id: DateTime.now().millisecondsSinceEpoch ~/ 1000,
title: '日常待办',
content: '',
isCompleted: false,
dueDate: null,

View File

@@ -17,7 +17,7 @@ class TodoAdapter extends TypeAdapter<Todo> {
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Todo(
id: fields[0] as int,
id: fields[0] as int?,
title: fields[1] as String,
content: fields[2] as String,
isCompleted: fields[3] as bool,

View File

@@ -1,25 +1,42 @@
import 'package:flisp_app/widgets/common.dart';
import 'package:flutter/material.dart';
import 'package:flutter_quill/flutter_quill.dart';
class FlashPage extends StatelessWidget {
class FlashPage extends StatefulWidget {
const FlashPage({super.key});
@override
_FlashPageState createState() => _FlashPageState();
}
class _FlashPageState extends State<FlashPage> {
late QuillController _controller;
@override
void initState() {
super.initState();
_controller = QuillController.basic();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return buildBody(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.flash_on, size: 80, color: Colors.blue),
SizedBox(height: 20),
Text(
'闪灵',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
QuillSimpleToolbar(
controller: _controller,
config: const QuillSimpleToolbarConfig(),
),
SizedBox(height: 10),
Text(
'快速记录你的灵感瞬间',
style: TextStyle(fontSize: 16, color: Colors.grey),
Expanded(
child: QuillEditor.basic(
controller: _controller,
config: const QuillEditorConfig(),
),
),
],
),

View File

@@ -1,28 +0,0 @@
import 'package:flisp_app/widgets/common.dart';
import 'package:flutter/material.dart';
class NotesPage extends StatelessWidget {
const NotesPage({super.key});
@override
Widget build(BuildContext context) {
return buildBody(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.note, size: 80, color: Colors.green),
SizedBox(height: 20),
Text(
'笔记',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
Text(
'管理你的所有笔记',
style: TextStyle(fontSize: 16, color: Colors.grey),
),
],
),
);
}
}

View File

@@ -1,28 +1,171 @@
import 'package:flisp_app/widgets/common.dart';
import 'package:flisp_app/models/reminder.dart';
import 'package:flisp_app/provider/reminder_provider.dart';
import 'package:flisp_app/service/reminder_service.dart';
import 'package:flisp_app/utils/notify_utils.dart';
import 'package:flisp_app/widgets/awesome_dialog.dart';
import 'package:flisp_app/widgets/reminder_form.dart';
import 'package:flisp_app/widgets/reminder_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:provider/provider.dart';
import 'package:flisp_app/widgets/common.dart';
class RemindersPage extends StatelessWidget {
const RemindersPage({super.key});
class RemindersPage extends StatefulWidget {
final VoidCallback? onAddPressed;
const RemindersPage({super.key, this.onAddPressed});
@override
State<RemindersPage> createState() => ReminderPageState();
}
class ReminderPageState extends State<RemindersPage> {
final ReminderService reminderService = ReminderService();
final NotifyService notifyService = NotifyService();
List<Reminder> _reminders = [];
void showAddDialog() {
_showDialog(false, null);
}
@override
void initState() {
super.initState();
_loadReminders();
}
Future<void> _loadReminders() async {
final reminders = await updateReminders();
if (mounted) {
setState(() {
_reminders = reminders;
});
}
}
Future<List<Reminder>> updateReminders() async {
// 获取flutter_local_notifications中所有的通知ID
final pendingNotifications = await notifyService.getPendingNotifications();
print("notifyService: ${pendingNotifications.length}");
final notificationIds = pendingNotifications.map((n) => n.id).toSet();
// 获取Hive中所有的提醒
final hiveReminders = reminderService.getAllReminders();
print("hiveReminders: ${hiveReminders.length}");
final hiveReminderIds = hiveReminders.map((r) => r.id).toSet();
// 情况1删除Hive中存在但通知中不存在的提醒已触发或已取消
final remindersToDeleteFromHive =
hiveReminders.where((reminder) {
return !notificationIds.contains(reminder.id);
}).toList();
for (final reminder in remindersToDeleteFromHive) {
await reminderService.deleteReminder(reminder);
}
// 情况2对于通知中存在但Hive中不存在的提醒重新创建保留时间等完整信息
final remindersToRecreate =
pendingNotifications.where((notification) {
return !hiveReminderIds.contains(notification.id);
}).toList();
for (final notification in remindersToRecreate) {
final newReminder = Reminder(
id: notification.id,
title: notification.title ?? '新提醒',
content: notification.body ?? '',
scheduledTime: DateTime.now().add(const Duration(days: 1)),
);
await reminderService.addReminder(newReminder);
}
// 更新本地列表
_reminders = reminderService.getAllReminders();
return _reminders;
}
@override
Widget build(BuildContext context) {
return buildBody(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.notifications, size: 80, color: Colors.red),
SizedBox(height: 20),
Text(
'提醒任务',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
Text(
'设置重要提醒',
style: TextStyle(fontSize: 16, color: Colors.grey),
Expanded(
child: buildReminderList(
reminders: _reminders,
onEditReminder: (reminder) {
_showDialog(true, reminder);
},
),
),
],
),
);
}
}
// 显示对话框
void _showDialog(bool isEditing, Reminder? reminder) {
final reminderProvider = Provider.of<ReminderProvider>(
context,
listen: false,
);
if (isEditing) {
reminderProvider.initForm(reminder!);
} else {
reminderProvider.resetForm();
}
final formKey = GlobalKey<FormBuilderState>();
showAwesomeDialog(
context: context,
body: ReminderForm(
formKey: formKey,
isEditing: isEditing,
initialReminder: reminder,
),
onOk: () {
if (formKey.currentState!.saveAndValidate()) {
Navigator.of(context).pop();
_saveOrUpdateReminder(isEditing, reminderProvider.formItem);
}
},
onCancel: () {
reminderProvider.resetForm();
},
);
}
// 保存提醒事项
void _saveOrUpdateReminder(bool isEditing, Reminder reminder) async {
late bool isSuccess;
if (isEditing) {
// 先删除
await notifyService.cancelNotification(reminder.id);
await reminderService.deleteReminder(reminder);
// 在重新新建
reminder.id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
}
isSuccess = await reminderService.addReminder(reminder);
await notifyService.scheduleNotification(
id: reminder.id,
title: reminder.title,
body: reminder.content,
scheduledTime: reminder.scheduledTime,
);
await _loadReminders();
if (isSuccess) {
showSuccessDialog(context, isEditing ? '更新成功' : '添加成功');
} else {
showErrorDialog(context, isEditing ? '更新失败' : '添加失败');
}
}
}

View File

@@ -28,8 +28,8 @@ class TodoPageState extends State<TodoPage> {
// 获取过滤后的待办事项
List<Todo> get _activeTodos => getActiveTodos(_currentTab, _todos);
void showAddTodoDialog() {
_showTodoDialog(false, null);
void showAddDialog() {
_showDialog(false, null);
}
@override
@@ -65,16 +65,16 @@ class TodoPageState extends State<TodoPage> {
return _activeTodos.isEmpty
? buildEmptyState(_currentTab)
: buildTodoList(
todos: _activeTodos,
onToggleTodo: (todo) {
setState(() {
_toggleTodo(todo);
});
},
onEditTodo: (todo) {
_showTodoDialog(true, todo);
},
);
todos: _activeTodos,
onToggleTodo: (todo) {
setState(() {
_toggleTodo(todo);
});
},
onEditTodo: (todo) {
_showDialog(true, todo);
},
);
}
// 切换待办事项完成状态
@@ -85,7 +85,7 @@ class TodoPageState extends State<TodoPage> {
}
// 显示对话框
void _showTodoDialog(bool isEditing, Todo? todo) {
void _showDialog(bool isEditing, Todo? todo) {
final todoProvider = Provider.of<TodoProvider>(context, listen: false);
if (isEditing) {
@@ -113,7 +113,7 @@ class TodoPageState extends State<TodoPage> {
// 保存待办事项
void _saveTodo(bool isEditing, Todo todo) async {
late bool isSuccess ;
late bool isSuccess;
if (isEditing) {
isSuccess = await todoService.updateTodo(todo);
} else {

View File

@@ -0,0 +1,18 @@
import 'package:flisp_app/models/reminder.dart';
import 'package:flutter/material.dart';
class ReminderProvider with ChangeNotifier {
late Reminder _formItem;
Reminder get formItem => _formItem;
void resetForm() {
_formItem = Reminder.getEmpty();
notifyListeners();
}
void initForm(Reminder reminder) {
_formItem = reminder;
notifyListeners();
}
}

View File

@@ -0,0 +1,39 @@
import 'package:flisp_app/models/reminder.dart';
import 'package:hive_flutter/hive_flutter.dart';
class ReminderService {
static const String boxName = 'reminders';
Box<Reminder> get box => Hive.box<Reminder>(boxName);
Future<bool> addReminder(Reminder reminder) async {
try {
await box.add(reminder);
return true;
} catch (e) {
return false;
}
}
List<Reminder> getAllReminders() {
return box.values.toList();
}
Future<bool> updateReminder(Reminder reminder) async {
try {
await reminder.save();
return true;
} catch (e) {
return false;
}
}
Future<bool> deleteReminder(Reminder reminder) async {
try {
await reminder.delete();
return true;
} catch (e) {
return false;
}
}
}

View File

@@ -1,3 +1,7 @@
String formatDate(DateTime date) {
return '${date.month}${date.day}';
}
// String formatDate(DateTime date) {
// return '${date.month}月${date.day}日';
// }
//
// String formatTime(DateTime datetime) {
// return '${datetime.year}-${datetime.month}-${datetime.day} ${datetime.hour}:${datetime.minute}:${datetime.second}';
// }

146
lib/utils/notify_utils.dart Normal file
View File

@@ -0,0 +1,146 @@
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
class NotifyService {
static final NotifyService _instance = NotifyService._internal();
factory NotifyService() => _instance;
NotifyService._internal();
late FlutterLocalNotificationsPlugin _notifications;
// 使用绝对时间(而不是相对时间),避免时区转换问题。
final dateInterpretation = UILocalNotificationDateInterpretation.absoluteTime;
// Android特殊模式即使设备处于省电模式也能准时触发。
final scheduleMode = AndroidScheduleMode.exactAllowWhileIdle;
// 初始化通知服务
Future<void> initialize() async {
_notifications = FlutterLocalNotificationsPlugin();
// 初始化时区
tz.initializeTimeZones();
// String timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation("Asia/Shanghai"));
// 设置Android平台的初始化配置 使用应用图标作为通知图标
const AndroidInitializationSettings androidSettings =
AndroidInitializationSettings('@mipmap/ic_launcher');
// 设置iOS平台的初始化配置
const DarwinInitializationSettings iosSettings =
DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
// 初始化设置
const InitializationSettings settings = InitializationSettings(
android: androidSettings,
iOS: iosSettings,
);
await _notifications.initialize(settings);
}
// 创建Android通知详情
AndroidNotificationDetails _androidNotificationDetails() {
const channelId = 'com.cxx.flisp_app';
const channelName = '闪灵';
const channelDescription = '闪灵通知';
return const AndroidNotificationDetails(
channelId,
channelName,
channelDescription: channelDescription,
importance: Importance.high,
priority: Priority.high,
playSound: true,
enableVibration: true,
);
}
// 创建iOS通知详情
DarwinNotificationDetails _iosNotificationDetails() {
return const DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
);
}
NotificationDetails get _details {
return NotificationDetails(
android: _androidNotificationDetails(),
iOS: _iosNotificationDetails(),
);
}
// 立即显示通知
Future<void> showInstantNotification({
required String title,
required String body,
int id = 0,
}) async {
await _notifications.show(id, title, body, _details);
}
// 安排定时通知
Future<void> scheduleNotification({
required int id,
required String title,
required String body,
required DateTime scheduledTime,
}) async {
print("scheduleNotification: $id");
await _notifications.zonedSchedule(
id,
title,
body,
tz.TZDateTime.from(scheduledTime, tz.local),
_details,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
);
}
// 取消特定通知
Future<void> cancelNotification(int id) async {
print("cancelNotification: $id");
await _notifications.cancel(id);
}
// 取消所有通知
Future<void> cancelAllNotifications() async {
await _notifications.cancelAll();
}
// 检查通知权限
Future<bool> checkPermission() async {
final bool? result =
await _notifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>()
?.areNotificationsEnabled();
return result ?? false;
}
// 请求权限
Future<void> requestPermission() async {
await _notifications
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>()
?.requestPermissions(alert: true, badge: true, sound: true);
}
// 获取所有待处理的通知
Future<List<PendingNotificationRequest>> getPendingNotifications() async {
return await _notifications.pendingNotificationRequests();
}
}

View File

@@ -0,0 +1,208 @@
import 'package:flisp_app/models/reminder.dart';
import 'package:flisp_app/provider/reminder_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:flisp_app/utils/date_utils.dart';
class ReminderForm extends StatefulWidget {
final GlobalKey<FormBuilderState> formKey;
final bool isEditing;
final Reminder? initialReminder;
const ReminderForm({
super.key,
required this.formKey,
required this.isEditing,
this.initialReminder,
});
@override
State<ReminderForm> createState() => _ReminderFormState();
}
class _ReminderFormState extends State<ReminderForm> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
final int maxTitleCount = 10;
final int maxContentCount = 20;
final provider = Provider.of<ReminderProvider>(context);
Widget buildTitle() {
return Row(
children: [
Icon(
widget.isEditing ? Icons.edit_note : Icons.add_task,
color: Colors.orange,
size: 24,
),
SizedBox(width: 8),
Text(
widget.isEditing ? '编辑提醒事项' : '添加提醒事项',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.orange,
),
),
],
);
}
FormBuilderTextField buildTitleField() {
return FormBuilderTextField(
name: 'title',
initialValue: provider.formItem.title,
onChanged: (value) {
setState(() {
provider.formItem.title = value ?? '';
});
},
decoration: InputDecoration(
labelText: '标题',
hintText: '请输入提醒事项标题...',
counterText: '',
suffixText: '${provider.formItem.title.length}/$maxTitleCount',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.grey.shade200),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.grey.shade200),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.orange),
),
filled: true,
fillColor: Colors.white,
prefixIcon: Icon(Icons.title, color: Colors.blue),
contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
),
maxLength: maxTitleCount,
validator: (value) {
if (value == null || value.isEmpty) {
return '请输入标题';
}
if (value.length > maxTitleCount) {
return '标题不能超过$maxTitleCount个字符';
}
return null;
},
);
}
FormBuilderTextField buildContentField() {
return FormBuilderTextField(
name: 'content',
initialValue: provider.formItem.content,
onChanged: (value) {
setState(() {
provider.formItem.content = value ?? '';
});
},
decoration: InputDecoration(
labelText: '内容',
hintText: '请输入提醒事项内容...',
counterText: '',
suffixText: '${provider.formItem.content.length}/$maxContentCount',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.grey.shade200),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.grey.shade200),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.orange),
),
filled: true,
fillColor: Colors.white,
prefixIcon: Icon(Icons.description, color: Colors.green),
contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
),
maxLines: 2,
maxLength: maxContentCount,
validator: (value) {
if (value != null && value.length > maxContentCount) {
return '内容不能超过$maxContentCount个字符';
}
return null;
},
);
}
FormBuilderDateTimePicker buildDateField() {
return FormBuilderDateTimePicker(
name: 'dueDate',
format: DateFormat('yyyy-MM-dd HH:mm:ss'),
initialValue: provider.formItem.scheduledTime,
inputType: InputType.both,
onChanged: (value) {
setState(() {
provider.formItem.scheduledTime = value!;
});
},
decoration: InputDecoration(
labelText: '提醒时间',
labelStyle: TextStyle(color: Colors.black87),
prefixIcon: Icon(Icons.calendar_today, color: Colors.purple),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.grey.shade200),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.grey.shade200),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.orange),
),
filled: true,
fillColor: Colors.white,
contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
),
validator: (value) {
if (value != null && value.isBefore(DateTime.now())) {
return '不能选择过去的时间';
}
return null;
},
);
}
FormBuilder buildForm() {
return FormBuilder(
key: widget.formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
buildTitleField(),
SizedBox(height: 12),
buildContentField(),
SizedBox(height: 12),
buildDateField(),
],
),
);
}
return Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [buildTitle(), SizedBox(height: 20), buildForm()],
),
);
}
}

View File

@@ -0,0 +1,96 @@
import 'package:flisp_app/models/reminder.dart';
import 'package:flisp_app/widgets/common.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
Widget buildReminderList({
required List<Reminder> reminders,
required ValueChanged<Reminder> onEditReminder,
}) {
return ListView.separated(
itemCount: reminders.length,
separatorBuilder: (context, index) => SizedBox(height: 8),
itemBuilder: (context, index) {
final reminder = reminders[index];
return _buildReminderItem(reminder: reminder, onEdit: onEditReminder);
},
);
}
Widget _buildReminderItem({
required Reminder reminder,
required ValueChanged<Reminder> onEdit,
}) {
return buildCard(
child: ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 0),
leading: Icon(Icons.notifications, color: Colors.blue),
title: _buildReminderTitle(reminder),
subtitle: _buildReminderSubtitle(reminder),
onTap: () => onEdit(reminder),
),
);
}
Widget _buildReminderTitle(Reminder reminder) {
return Text(
reminder.title,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
Widget _buildReminderSubtitle(Reminder reminder) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 4),
Text(
reminder.content,
style: TextStyle(
fontSize: 14,
color: Colors.grey[700],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
SizedBox(height: 8),
Container(
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.blue[50],
borderRadius: BorderRadius.circular(4),
),
child: Text(
DateFormat('MM月dd日 HH:mm').format(reminder.scheduledTime),
style: TextStyle(
fontSize: 12,
color: Colors.blue[700],
fontWeight: FontWeight.w500,
),
),
),
],
);
}
// 空状态
Widget buildEmptyState() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.task_alt, size: 80, color: Colors.orange.shade600),
Text(
'📋 还没有任何待办事项\n点击下方+号开始规划你的任务吧!',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.orange.shade600),
),
],
),
);
}

View File

@@ -1,9 +1,9 @@
import 'package:flisp_app/provider/todo_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:flisp_app/models/todo.dart';
import 'package:flisp_app/utils/date_utils.dart';
class TodoForm extends StatefulWidget {
final GlobalKey<FormBuilderState> formKey;
@@ -31,7 +31,7 @@ class _TodoFormState extends State<TodoForm> {
Widget build(BuildContext context) {
final int maxTitleCount = 10;
final int maxContentCount = 20;
final store = Provider.of<TodoProvider>(context);
final provider = Provider.of<TodoProvider>(context);
Widget buildTitle() {
return Row(
@@ -57,17 +57,17 @@ class _TodoFormState extends State<TodoForm> {
FormBuilderTextField buildTitleField() {
return FormBuilderTextField(
name: 'title',
initialValue: store.formItem.title,
initialValue: provider.formItem.title,
onChanged: (value) {
setState(() {
store.formItem.title = value ?? '';
provider.formItem.title = value ?? '';
});
},
decoration: InputDecoration(
labelText: '标题',
hintText: '请输入待办事项标题...',
counterText: '',
suffixText: '${store.formItem.title.length}/$maxTitleCount',
suffixText: '${provider.formItem.title.length}/$maxTitleCount',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.grey.shade200),
@@ -98,20 +98,20 @@ class _TodoFormState extends State<TodoForm> {
);
}
FormBuilderTextField buildDescriptionField() {
FormBuilderTextField buildContentField() {
return FormBuilderTextField(
name: 'description',
initialValue: store.formItem.content,
name: 'content',
initialValue: provider.formItem.content,
onChanged: (value) {
setState(() {
store.formItem.content = value ?? '';
provider.formItem.content = value ?? '';
});
},
decoration: InputDecoration(
labelText: '内容',
hintText: '请输入待办事项内容...',
counterText: '',
suffixText: '${store.formItem.content.length}/$maxContentCount',
suffixText: '${provider.formItem.content.length}/$maxContentCount',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.grey.shade200),
@@ -145,7 +145,7 @@ class _TodoFormState extends State<TodoForm> {
icon: Icon(Icons.clear, size: 18),
onPressed: () {
setState(() {
store.formItem.dueDate = null;
provider.formItem.dueDate = null;
});
widget.formKey.currentState?.fields['dueDate']?.didChange(null);
},
@@ -155,21 +155,24 @@ class _TodoFormState extends State<TodoForm> {
FormBuilderDateTimePicker buildDateField() {
return FormBuilderDateTimePicker(
name: 'dueDate',
initialValue: store.formItem.dueDate,
format: DateFormat('yyyy-MM-dd'),
initialValue: provider.formItem.dueDate,
inputType: InputType.date,
onChanged: (value) {
setState(() {
store.formItem.dueDate = value;
provider.formItem.dueDate = value;
});
},
decoration: InputDecoration(
labelText:
store.formItem.dueDate == null
provider.formItem.dueDate == null
? '选择截止日期'
: '截止: ${formatDate(store.formItem.dueDate!)}',
: '截止: ${DateFormat('yyyy-MM-dd').format(provider.formItem.dueDate!)}',
labelStyle: TextStyle(
color:
store.formItem.dueDate == null ? Colors.grey : Colors.black87,
provider.formItem.dueDate == null
? Colors.grey
: Colors.black87,
),
prefixIcon: Icon(Icons.calendar_today, color: Colors.purple),
border: OutlineInputBorder(
@@ -188,7 +191,7 @@ class _TodoFormState extends State<TodoForm> {
fillColor: Colors.white,
contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
suffixIcon:
store.formItem.dueDate != null
provider.formItem.dueDate != null
? buildClearDateSuffixIcon()
: null,
),
@@ -205,7 +208,7 @@ class _TodoFormState extends State<TodoForm> {
FormBuilderRadioGroup builderRadioGroup() {
return FormBuilderRadioGroup<TodoPriority>(
name: 'priority',
initialValue: store.formItem.priority,
initialValue: provider.formItem.priority,
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.zero,
@@ -225,7 +228,7 @@ class _TodoFormState extends State<TodoForm> {
onChanged: (value) {
if (value != null) {
setState(() {
store.formItem.priority = value;
provider.formItem.priority = value;
});
}
},
@@ -264,7 +267,7 @@ class _TodoFormState extends State<TodoForm> {
children: [
buildTitleField(),
SizedBox(height: 12),
buildDescriptionField(),
buildContentField(),
SizedBox(height: 12),
buildDateField(),
SizedBox(height: 12),

View File

@@ -1,7 +1,7 @@
import 'package:flisp_app/models/todo.dart';
import 'package:flisp_app/utils/date_utils.dart';
import 'package:flisp_app/widgets/common.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:toggle_switch/toggle_switch.dart';
// 统计卡片
@@ -119,6 +119,7 @@ Widget _buildTodoTitle(Todo todo) {
style: TextStyle(
decoration: todo.isCompleted ? TextDecoration.lineThrough : null,
color: todo.isCompleted ? Colors.grey : null,
fontSize: 16,
fontWeight: FontWeight.w500,
),
);
@@ -128,31 +129,45 @@ Widget _buildTodoTitle(Todo todo) {
Widget? _buildTodoSubtitle(Todo todo) {
final isOverdue =
todo.dueDate != null &&
todo.dueDate!.isBefore(DateTime.now()) &&
!todo.isCompleted;
todo.dueDate!.isBefore(DateTime.now()) &&
!todo.isCompleted;
final hasContent = todo.content.isNotEmpty == true || todo.dueDate != null;
if (!hasContent) return null;
return Wrap(
direction: Axis.vertical,
spacing: 5,
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 4),
if (todo.content.isNotEmpty == true)
Text(
todo.content,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
),
if (todo.dueDate != null)
Text(
'截止: ${formatDate(todo.dueDate!)}',
style: TextStyle(
fontSize: 11,
color: isOverdue ? Colors.red : Colors.grey,
fontWeight: isOverdue ? FontWeight.bold : FontWeight.normal,
fontSize: 14,
color: Colors.grey[700],
),
),
SizedBox(height: 8),
if (todo.dueDate != null)
Container(
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: isOverdue ? Colors.red[50] : Colors.grey[50],
borderRadius: BorderRadius.circular(4),
border: Border.all(
color: isOverdue ? Colors.red[100]! : Colors.grey[300]!,
),
),
child: Text(
'截止: ${DateFormat("yyyy-MM-dd").format(todo.dueDate!)}',
style: TextStyle(
fontSize: 11,
color: isOverdue ? Colors.red[600] : Colors.grey[600],
fontWeight: isOverdue ? FontWeight.w600 : FontWeight.normal,
),
),
),
],