我正在使用Provider Package和ListView.Builder在混乱中构建简单的TodoList应用程序。
TaskModel.dart
class TaskModel { //Model class for the data to be stored
String task;
bool isCompleted;
String get getTask => task;
bool get getIsCompleted => isCompleted;
TaskModel({this.task, this.isCompleted});
}
Tasker.dart
class Tasker extends ChangeNotifier {
List<TaskModel> myTasks = [];
void addTask(TaskModel taskToAdd) {
myTasks.add(taskToAdd);
notifyListeners();
}
}
现在有ListView.Builder,我正在尝试从Tasker类访问myTasks。
Consumer<Tasker>(
builder: (context, newTask, child) {
return ListView.builder(
itemCount: newTask.myTasks.length, //The error is when accessing newTask.myTasks
itemBuilder: (context, index) {
return ListTile(.....);
});
},
),
错误消息是*
getter'myTasks'在null上被调用。接收方:null尝试调用: myTasks
*
我认为您想念提供者,而该提供者将类连接起来,因为如果不先定义它就无法检测到您的模型
return ChangeNotifierProvider<TaskModel>( // <--- ChangeNotifierProvider
create: (context) => TaskModel(),
child:Consumer<Tasker>(
builder: (context, newTask, child) {
return ListView.builder(
itemCount: newTask.myTasks.length, //The error is when accessing newTask.myTasks
itemBuilder: (context, index) {
return ListTile(.....);
});
},
),