Skip to content
This repository was archived by the owner on Feb 22, 2023. It is now read-only.

[Sensors] Fix:avoid calling setState() when mounted is false. #2361

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/sensors/example/lib/snake.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,14 @@ class SnakeState extends State<Snake> {
void initState() {
super.initState();
accelerometerEvents.listen((AccelerometerEvent event) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The return value of listen is a StreamSubscription<AccelerometerEvent>. That should move into a _accelerometerEventSubscription field. Please cancel() it in the dispose method.

if (!mounted) return;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add { and } to make things a bit cleared in the sample

setState(() {
acceleration = event;
});
});

Timer.periodic(const Duration(milliseconds: 200), (_) {
if (!mounted) return;
Copy link
Contributor

@ened ened Dec 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can actually replace the _ with timer and then cancel the timer as well, when not mounted.

Perhaps keep the timer in a _timer field and cancel in the dispose method as above. Sorry.

setState(() {
_step();
});
Expand Down