【Flutter Todo 实战】第十章:扩展功能建议

· 4 min read

恭喜你已经完成了基础的待办事项应用!本章将提供一些扩展功能的建议,帮助你继续提升这个应用。

10.1 功能扩展

1. 任务分类

添加任务分类功能,让用户可以按类别组织任务。

实现思路:

// 新增 Category 模型
class Category {
  final String id;
  final String name;
  final Color color;
  final IconData icon;
}

// Task 模型添加 categoryId
class Task {
  ...
  final String? categoryId;
}

UI 变化:

  • 添加任务时选择分类
  • 按分类筛选任务
  • 显示分类统计

2. 任务优先级

为任务添加优先级(高/中/低)。

实现思路:

enum Priority {
  high('高', Colors.red),
  medium('中', Colors.orange),
  low('低', Colors.green);
  
  final String label;
  final Color color;
}

class Task {
  ...
  final Priority priority;
}

UI 变化:

  • 任务项显示优先级标识
  • 按优先级排序
  • 筛选特定优先级的任务

3. 任务提醒

添加本地通知提醒功能。

实现思路:

1# pubspec.yaml
2dependencies:
3  flutter_local_notifications: ^16.3.0
// 设置提醒
Future scheduleReminder(Task task) async {
  if (task.dueDate != null) {
    await notificationsPlugin.schedule(
      task.id.hashCode,
      '任务提醒',
      task.title,
      task.dueDate!.subtract(Duration(minutes: 30)),  // 提前30分钟
      ...
    );
  }
}

4. 搜索功能

添加任务搜索功能。

实现思路:

// Provider 中添加搜索方法
List searchTasks(String query) {
  return _tasks.where((task) =>
    task.title.toLowerCase().contains(query.toLowerCase())
  ).toList();
}

// UI 中添加搜索栏
TextField(
  onChanged: (value) => provider.search(value),
  decoration: InputDecoration(
    hintText: '搜索任务...',
    prefixIcon: Icon(Icons.search),
  ),
)

5. 数据统计

添加任务完成统计页面。

实现思路:

class TaskStats {
  final int totalTasks;
  final int completedTasks;
  final int completionRate;  // 完成率
  final Map dailyCompletions;  // 每日完成数
}

UI 设计:

  • 饼图显示完成比例
  • 柱状图显示每日完成数
  • 连续完成天数统计

6. 数据同步

添加云同步功能,支持多设备同步。

可选方案:

方案 优点 缺点
Firebase 免费、易用、实时同步 需要网络
Supabase 开源、PostgreSQL 配置较复杂
自建后端 完全控制 维护成本高

Firebase 示例:

1dependencies:
2  firebase_core: ^2.24.2
3  cloud_firestore: ^4.14.0
// 同步任务到云端
Future syncToCloud(List tasks) async {
  final userId = FirebaseAuth.instance.currentUser!.uid;
  final batch = FirebaseFirestore.instance.batch();
  
  for (final task in tasks) {
    final ref = FirebaseFirestore.instance
        .collection('users')
        .doc(userId)
        .collection('tasks')
        .doc(task.id);
    batch.set(ref, task.toJson());
  }
  
  await batch.commit();
}

10.2 UI 改进

1. 动画效果

添加动画让应用更生动。

// 任务添加动画
AnimatedList(
  key: _listKey,
  initialItemCount: tasks.length,
  itemBuilder: (context, index, animation) {
    return SizeTransition(
      sizeFactor: animation,
      child: TaskItem(task: tasks[index]),
    );
  },
)

// 页面切换动画
PageTransitionSwitcher(
  transitionBuilder: (child, primaryAnimation, secondaryAnimation) {
    return FadeThroughTransition(
      animation: primaryAnimation,
      secondaryAnimation: secondaryAnimation,
      child: child,
    );
  },
  child: currentScreen,
)

2. 自定义主题

让用户可以选择主题颜色。

class ThemeProvider extends ChangeNotifier {
  Color _seedColor = Color(0xFF6750A4);
  
  void setSeedColor(Color color) {
    _seedColor = color;
    notifyListeners();
  }
  
  ThemeData get theme => ThemeData(
    colorScheme: ColorScheme.fromSeed(seedColor: _seedColor),
  );
}

3. 手势操作

添加更多手势支持。

// 长按菜单
gestureDetector: GestureDetector(
  onLongPress: () => showContextMenu(task),
  child: TaskItem(...),
)

// 拖拽排序
ReorderableListView(
  onReorder: (oldIndex, newIndex) {
    provider.reorderTasks(oldIndex, newIndex);
  },
  children: tasks.map((task) => TaskItem(task: task)).toList(),
)

10.3 代码优化

1. 单元测试

添加测试保证代码质量。

// test/task_provider_test.dart
import 'package:flutter_test/flutter_test.dart';

void main() {
  group('TaskProvider', () {
    late TaskProvider provider;
    
    setUp(() {
      provider = TaskProvider();
    });
    
    test('should add task', () async {
      await provider.addTask('测试任务');
      expect(provider.totalTaskCount, 1);
    });
    
    test('should toggle task', () async {
      await provider.addTask('测试任务');
      final taskId = provider.tasks.first.id;
      
      await provider.toggleTask(taskId);
      expect(provider.tasks.first.isCompleted, true);
    });
  });
}

2. 代码规范

使用 lint 规则保持代码质量。

1# analysis_options.yaml
2include: package:flutter_lints/flutter.yaml
3
4linter:
5  rules:
6    prefer_single_quotes: true
7    prefer_const_constructors: true
8    avoid_print: true

3. 国际化

支持多语言。

1dependencies:
2  flutter_localizations:
3    sdk: flutter
4  intl: ^0.18.1
// 使用本地化
AppLocalizations.of(context)!.taskAdded

// l10n/app_zh.arb
{
  "taskAdded": "任务已添加",
  "taskDeleted": "任务已删除"
}

10.4 发布准备

1. 应用图标

为应用设计图标。

1# 使用 flutter_launcher_icons
2flutter pub add flutter_launcher_icons
3
4# 配置 pubspec.yaml
5flutter_icons:
6  android: true
7  ios: true
8  image_path: "assets/icon.png"
9
10# 生成图标
11flutter pub run flutter_launcher_icons:main

2. 应用名称

修改应用显示名称。

1
1
2<key>CFBundleDisplayNamekey>
3<string>待办事项string>  

3. 签名配置

配置发布签名。

Android:

// android/app/build.gradle
android {
    signingConfigs {
        release {
            keyAlias 'your_alias'
            keyPassword 'your_password'
            storeFile file('your_key.jks')
            storePassword 'your_password'
        }
    }
}

4. 构建发布版本

1# Android APK
2flutter build apk --release
3
4# Android App Bundle(推荐)
5flutter build appbundle --release
6
7# iOS
8flutter build ios --release

10.5 学习资源

官方资源

推荐书籍

  • 《Flutter 实战》
  • 《Flutter 技术解析与实战》

推荐课程

  • Flutter 官方 Codelabs
  • YouTube Flutter 频道

社区资源

10.6 结语

恭喜你完成了整个待办事项应用的教程!

通过这个教程,你学会了:

  • ✅ Flutter 环境搭建
  • ✅ Widget 和 State 的概念
  • ✅ 项目结构组织
  • ✅ 数据模型设计
  • ✅ Provider 状态管理
  • ✅ Material Design 3 UI 设计
  • ✅ SharedPreferences 本地存储
  • ✅ 常见问题排查

下一步建议:

  1. 尝试实现本章提到的扩展功能
  2. 阅读 Flutter 官方文档深入学习
  3. 参与开源项目积累经验
  4. 构建自己的 Flutter 应用

祝你在 Flutter 开发的道路上越走越远!🚀

Related Articles