我想为我的应用程序实现 Provider,经过一些研究,我发现我必须为我的 Data 类实现 ChangeNotifier,以便在“天”更改时更新 UI。
\n\n我见过有人在 setter 方法中编写 notificationListeners() 但总是针对单个属性而不是针对列表。什么是正确的实施?
\n\n谢谢 !
\n\n这是我的班级和清单:
\n\nclass Data with ChangeNotifier {\n List<Day> days = [\n Day(\n name: \'Monday\',\n transactions: [\n Transaction(\n isExpense: true,\n name: \'Pizza\',\n transactionType: TransactionType.food,\n amount: \'120\xe2\x82\xac\',\n ),\n Transaction(\n isExpense: true,\n name: \'EDEKA\',\n transactionType: TransactionType.payment,\n amount: \'120\xe2\x82\xac\',\n ),\n ],\n ),\n Day(\n name: \'Tuesday\',\n transactions: [\n Transaction(\n isExpense: true,\n name: \'Sushi\',\n transactionType: TransactionType.food,\n amount: \'120\xe2\x82\xac\',\n ),\n Transaction(\n isExpense: true,\n name: \'Lidl\',\n transactionType: TransactionType.payment,\n amount: \'120\xe2\x82\xac\',\n ),\n Transaction(\n isExpense: false,\n name: \'Einkommen\',\n transactionType: TransactionType.payment,\n amount: \'120\xe2\x82\xac\',\n ),\n ],\n ),\n ];\n}\nRun Code Online (Sandbox Code Playgroud)\n
Todo App是一个很好的示例处理List<Taks>
您可以参考https://dev.to/shakib609/create-a-todos-app-with-flutter-and-provider-jdh
完整示例github代码https://github.com/ shakib609/todos-flutter/tree/master/lib
代码片段
class Task {
String title;
bool completed;
Task({@required this.title, this.completed = false});
void toggleCompleted() {
completed = !completed;
}
}
class TodosModel extends ChangeNotifier {
final List<Task> _tasks = [];
UnmodifiableListView<Task> get allTasks => UnmodifiableListView(_tasks);
UnmodifiableListView<Task> get incompleteTasks =>
UnmodifiableListView(_tasks.where((todo) => !todo.completed));
UnmodifiableListView<Task> get completedTasks =>
UnmodifiableListView(_tasks.where((todo) => todo.completed));
void addTodo(Task task) {
_tasks.add(task);
notifyListeners();
}
void toggleTodo(Task task) {
final taskIndex = _tasks.indexOf(task);
_tasks[taskIndex].toggleCompleted();
notifyListeners();
}
void deleteTodo(Task task) {
_tasks.remove(task);
notifyListeners();
}
}
Run Code Online (Sandbox Code Playgroud)
工作演示
| 归档时间: |
|
| 查看次数: |
5925 次 |
| 最近记录: |