我正在尝试使用这个示例来实现flutter包“计步器”。
我在加载的第一个页面中从 initState() 调用提供程序方法。 问题是计步器监听器/流在初始应用程序安装时不起作用,重新启动后所有接缝都按预期工作。
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
final myProvider = Provider.of<MyProvider>(context, listen: false);
myProvider.initPlatformState();
});
我的提供者类别:
class MyProvider extends ChangeNotifier {
...
late Stream<StepCount> _stepCountStream;
late Stream<PedestrianStatus> _pedestrianStatusStream;
void initPlatformState() {
Stream<PedestrianStatus> _pedestrianStatusStream = Pedometer.pedestrianStatusStream;
pedestrianStatusStream
.listen(onPedestrianStatusChanged)
.onError(onPedestrianStatusError);
Stream<StepCount> _stepCountStream = Pedometer.stepCountStream;
stepCountStream.listen(onStepCount).onError(onStepCountError);
}
}
I tried to move Stream variables into initPlatformState() but same result.
I added permissions and all...
Working only if i hot restart or go to other page and reload Provider.of<MyProvider>(context, listen: false).initPlatformState();
试试这个:
class MyProvider extends ChangeNotifier {
...
late Stream<StepCount> _stepCountStream;
late Stream<PedestrianStatus> _pedestrianStatusStream;
void initPlatformState() {
Stream<PedestrianStatus> _pedestrianStatusStream = Pedometer.pedestrianStatusStream;
pedestrianStatusStream
.listen(onPedestrianStatusChanged)
.onError(onPedestrianStatusError);
Stream<StepCount> _stepCountStream = Pedometer.stepCountStream;
stepCountStream.listen(onStepCount).onError(onStepCountError);
notifyListeners();
}
}