Why does flutter_compass sometimes show incorrect heading?

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 ?

Does this happen on every device? How long does it point in the wrong direction? Does it come back on it’s own?

You could try another compass app to see if the compass is really misbehaving or something is wrong with the compass package.

Checked on 4 phones - 2 androids and 2 iphones - on iphones it happens less often - usually when it shows the wrong direction it lasts until I don’t calibrate the compass or turn on airplane mode and turn it off. it is not the fault of the package but rather that the sensor from the compass returns data wrong - just a question of how you can calibrate the compass from within the application if turning on airplane mode helps, then somehow it can be done.

this should show up in other apps too if it’s the sensos. I saw some nice free compass apps for android, you should try if they behave the same