Main App File

The entire source for this simple app is found in lib/main.dart:

The Dart math library is imported, along with the flutter_compass package. The CompassDemo class builds a MaterialApp with a standard title, theme, and a home screen, which consists of a Scaffold with an AppBar and an instance of the Compass widget as the body.

The Compass class itself is an implementation of StatefulWidget, which is a widget that can retain mutable State data. The state for this compass class has a _heading property, and an accessor for readout which returns the heading as a string in degree format. The initState method sets up an event listener on the compass plugin, which will be called when the heading changes (i.e. the user moves and the compass angle changes). When the plugin event handler invokes onData with a new value, setState is called to update the heading and trigger a re-draw of the component UI.

The style for the readout is set with TextStyle on the _style property, and the widget’s build method returns a CustomPaint object, which will render the text readout for the heading, along with the compass circle and needle using CompassPainter as a foreground painter.