I’m using Flutter with flutter_compass and flutter_map to rotate the map based on the compass heading. Here’s a simplified version of my code:
import 'package:flutter/material.dart';
import 'package:flutter_compass/flutter_compass.dart';
import 'package:flutter_map/flutter_map.dart';
class CompassMapScreen extends StatefulWidget {
const CompassMapScreen({super.key});
@override
State<CompassMapScreen> createState() => _CompassMapScreenState();
}
class _CompassMapScreenState extends State<CompassMapScreen> {
double? _heading;
MapController mapController = MapController();
@override
void initState() {
super.initState();
FlutterCompass.events?.listen((event) {
if (event.heading != null) {
setState(() => _heading = event.heading);
mapController.rotate(-_heading!);
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('compass')),
body: Column(
children: [
Expanded(
child: FlutterMap(
mapController: mapController,
options: MapOptions(
initialZoom: 13.0,
),
children: [
TileLayer(
urlTemplate:
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.example.app',
),
],
),
),
],
),
);
}
}
Sometimes the compass shows the wrong direction, and the map rotates in the wrong direction. I noticed that when I manually turn on airplane mode and turn it off, the compass starts working correctly again - at least for some time.
My Questions: Why does this happen? Is the compass affected by magnetic interference?
Is there a way to reset or reinitialize flutter_compass programmatically, without telling the user to toggle airplane mode?
Is there a known workaround or fix to make the compass more reliable ?