Flutter待办事项 #

一、项目概述 #

待办事项应用学习本地存储、列表操作和状态管理。

二、核心代码 #

2.1 数据模型 #

dart
class Todo {
  final String id;
  String title;
  bool isCompleted;
  
  Todo({
    required this.id,
    required this.title,
    this.isCompleted = false,
  });
  
  Map<String, dynamic> toJson() => {
    'id': id,
    'title': title,
    'isCompleted': isCompleted,
  };
  
  factory Todo.fromJson(Map<String, dynamic> json) => Todo(
    id: json['id'],
    title: json['title'],
    isCompleted: json['isCompleted'],
  );
}

2.2 状态管理 #

dart
class TodoProvider extends ChangeNotifier {
  List<Todo> _todos = [];
  
  List<Todo> get todos => _todos;
  List<Todo> get completed => _todos.where((t) => t.isCompleted).toList();
  List<Todo> get pending => _todos.where((t) => !t.isCompleted).toList();
  
  void add(String title) {
    _todos.add(Todo(id: DateTime.now().toString(), title: title));
    notifyListeners();
  }
  
  void toggle(String id) {
    final index = _todos.indexWhere((t) => t.id == id);
    if (index != -1) {
      _todos[index].isCompleted = !_todos[index].isCompleted;
      notifyListeners();
    }
  }
  
  void remove(String id) {
    _todos.removeWhere((t) => t.id == id);
    notifyListeners();
  }
}

三、总结 #

待办事项应用展示了列表操作和本地存储。

3.1 下一步 #

让我们学习 天气应用

最后更新:2026-03-28