我无法理解一个小部件在另一个类中时不听而不是通知类的问题
我创建了一个“锻炼”课程:
class Exercise extends ChangeNotifier {
int duration;
Timer timer;
Exercise({@required this.duration});
void startExercise() {
timer = Timer.periodic(Duration(seconds: 1), (timer) { // <-- setting a timer that runs every second
if (duration > 0) {
duration -= 1;
notifyListeners();
} else {
timer.cancel();
}
});
}
}
我还有另一个将“运动”作为变量的类:
class Workout extends ChangeNotifier {
Exercise exercise = Exercise(duration: 100);
static final workout = Workout(); // <-- Creating a singleton
....
....
void setNewWorkout() {
....
....
this.exercise.duration = 100;
notifyListeners(); // <-- Here I expect that the exercise.duration will be updated
}
}
现在我有一个小部件,可以监听锻炼以及锻炼课程:
@override
Widget build(BuildContext context) {
return Scaffold(
body: ChangeNotifierProvider(
create: (context) => Workout.workout,
child: Consumer<Workout>(
builder: (context, workout, _) {
return Column(
children: [
Text("${workout.exercise.duration}"), // <-- Here I listen to the duration
FlatButton(
child: Text("Begin workout"),
onPressed: () {
workout.setNewWorkout();
workout.exercise.startExercise(); // <-- This is not working!!
}
)
]
);
}
)
)
}
现在这是棘手的部分。当我在初始化状态下调用Workout.workout.exercise.startExercise()
时。
一切正常,但是当锻炼结束时,我按一下按钮并创建新的锻炼,它将停止工作。
所以我认为,如果我要使“锻炼”单身,它将表现正常,而且确实如此!
我在Exercise类中添加了
static final Exercise current = Exercise(duration: 100);
现在在我的小部件中,我将文本包装在另一个变更通知程序提供程序中:
return Column(
...
...
ChangeNotifierProvider(
create: (context) => Exercise.current,
child: Consumer<Exercise>(
builder: (context, exercise, _) {
return Text("${exercise.duration}"), // <-- Now this is working
...
...
现在,当我的文字不在锻炼范围内时,它会监听单身人士! 为什么会这样呢?