Im trying to implement flutter package ‘Pedometer’ using this example.
Im calling provider methods from initState() in my first page loaded. Problem is pedometer listener/stream not working on initial app install, after restart everything seams working as expected.
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
final myProvider = Provider.of<MyProvider>(context, listen: false);
myProvider.initPlatformState();
});
My provider class:
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(context, listen: false).initPlatformState();
...SO notifyListeners() not fixing issue. Im trying now with streamBuilder, where I pass stream from above, but still I got stuck at 'ConnectionState.waiting' status
Widget build(BuildContext context) {
return Consumer<MyProvider>(builder: (context, value, child) {
return StreamBuilder(
stream: value.stepCountStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text('No data yet');
} else if (snapshot.connectionState == ConnectionState.done) {
return Text('Done');
} else if (snapshot.hasError) {
return Text('Error');
} else {
return Text(snapshot.data?.steps.toString() ?? '');
}
});
});
}
(until restart) so clearly something have to trigger stream?
1 Answer 1
try this:
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();
}
}
1 Comment
Explore related questions
See similar questions with these tags.