无此方法错误。该吸气剂被调用为null

问题描述 投票:0回答:1

我正在使用Provider PackageListView.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

*

flutter flutter-layout flutter-provider
1个回答
0
投票

我认为您想念提供者,而该提供者将类连接起来,因为如果不先定义它就无法检测到您的模型

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(.....);
                        });
                  },
                ),
© www.soinside.com 2019 - 2024. All rights reserved.