如何为与提供程序一起使用的列表实现ChangeNotifier?

时间:2020-02-13 19:44:16

标签: flutter dart

我想为我的应用程序实现Provider,经过一些研究后,我发现我必须为Data类实现ChangeNotifier才能在“天”更改时更新UI。

我见过人们在setter方法中编写notifyListeners(),但是总是针对单个属性,而不是列表。什么是正确的实现?

谢谢!

这是我的课程和清单:

class Data with ChangeNotifier {
  List<Day> days = [
    Day(
      name: 'Monday',
      transactions: [
        Transaction(
          isExpense: true,
          name: 'Pizza',
          transactionType: TransactionType.food,
          amount: '120€',
        ),
        Transaction(
          isExpense: true,
          name: 'EDEKA',
          transactionType: TransactionType.payment,
          amount: '120€',
        ),
      ],
    ),
    Day(
      name: 'Tuesday',
      transactions: [
        Transaction(
          isExpense: true,
          name: 'Sushi',
          transactionType: TransactionType.food,
          amount: '120€',
        ),
        Transaction(
          isExpense: true,
          name: 'Lidl',
          transactionType: TransactionType.payment,
          amount: '120€',
        ),
        Transaction(
          isExpense: false,
          name: 'Einkommen',
          transactionType: TransactionType.payment,
          amount: '120€',
        ),
      ],
    ),
  ];
}

2 个答案:

答案 0 :(得分:3)

有2种添加和删除项目的方法。

void add(Day day) {
  days.add(day);
  notifyListeners();
}

void remove(int index) {
  days.removeAt(index);
  notifyListeners();
}

答案 1 :(得分:3)

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();
  }
}

工作演示

enter image description here