我正在创建一个类似便笺的应用程序,其中包含可以添加的活动列表。我使用提供程序包将更改保存到列表。该列表由ListView.builder
创建,子级是由文本和复选框组成的ListTile
。我的编码没有错误,但是在调试中有一个错误“像我给的图像一样,“如果要公开可以是任何变量的变量,请考虑将动态更改为对象”。我该如何解决?
Main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:todoey_flutter/models/task_data.dart';
import 'screens/tasks_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => TaskData(),
lazy: false,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: TasksScreen(),
),
);
}
}
task_list.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'task_tile.dart';
class TaskList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer(
builder: (context, taskDataObject, child) {
return ListView.builder(
itemBuilder: (context, index) {
return TaskTile(
theTask: taskDataObject.tasks[index].name,
isChecked: taskDataObject.tasks[index].isDone,
checkboxCallback: (checkboxState) {
taskDataObject.updateTask(taskDataObject.tasks[index]);
},
);
},
itemCount: taskDataObject.taskCount,
);
},
);
}
}
task_tile.dart
import 'package:flutter/material.dart';
class TaskTile extends StatelessWidget {
TaskTile({
this.isChecked,
this.theTask,
this.checkboxCallback,
this.onLongPressCallback,
});
final bool isChecked;
final String theTask;
final Function checkboxCallback;
final Function onLongPressCallback;
@override
Widget build(BuildContext context) {
return ListTile(
onLongPress: onLongPressCallback,
title: Text(
theTask,
style: TextStyle(
decoration: isChecked ? TextDecoration.lineThrough : null),
),
trailing: Checkbox(
activeColor: Colors.lightBlueAccent,
value: isChecked,
onChanged: checkboxCallback,
),
);
}
}
提供商类
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:todoey_flutter/models/task.dart';
class TaskData extends ChangeNotifier {
List<Task> _tasks = [
Task(name: 'cook'),
Task(name: 'reading'),
Task(name: 'sleding')
];
int get taskCount {
return _tasks.length;
}
UnmodifiableListView<Task> get tasks {
return UnmodifiableListView(_tasks);
}
void addTask (String newTaskTitle) {
final task = Task(name: newTaskTitle);
_tasks.add(task);
notifyListeners();
}
void updateTask (Task task){
task.toggleDone();
notifyListeners();
}
void deleteTask (Task task){
_tasks.remove(task);
notifyListeners();
}
}
答案 0 :(得分:0)
您必须使用Consumer
中的T
,而不仅仅是Consumer
。因此,将task_list.dart
更改为:
class TaskList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<TaskData>( // <--- Here, insert <TaskData> after Consumer
builder: (context, taskDataObject, child) {
// ...
},
);
}
}