flutter_compass 0.4.2+1

  • Readme
  • Changelog
  • Example
  • Installing
  • 96

flutter_compass #

pub package

A Flutter compass. The heading varies from 0-360, 0 being north.

Note: Android Only: null is returned as direction on android when no sensor available.

Usage #

To use this plugin, add flutter_compass as a dependency in your pubspec.yaml file. For example:

dependencies:
  flutter_compass: '^0.4.1'

iOS #

Make sure to add keys with appropriate descriptions to the Info.plist file.

  • NSLocationWhenInUseUsageDescription
  • NSLocationAlwaysAndWhenInUseUsageDescription

📝 Reference example code

Android #

Make sure to add permissions to the app/src/main/AndroidManifest.xml file.

  • android.permission.INTERNET
  • android.permission.ACCESS_COARSE_LOCATIO
  • android.permission.ACCESS_FINE_LOCATION

📝 Reference example code

📝 Reference example code

0.4.2+1 #

Minor fix

0.4.2 #

Updated rxDart to 0.24.0

0.4.1 #

Updated README.md

0.4.0 #

Breaking change: Uses magnetic heading by default for iOS.

Older versions used True heading and which caused deviations.

0.3.7 #

  • Sensor check added on android. null is returned as direction when no sensor available.

0.3.6 #

  • Upgrade rxdart version to 0.23.1

0.3.5 #

  • Improve README.md

0.3.4 #

  • Add dispose method

0.3.3 #

  • Update permission_handler to 3.2.2
  • Update rxdart to 0.22.3

0.3.2 #

  • Android: The plugin will now remember the last read azimuth. This will be done across Isolates using a static variable. Additionally, the value is cached within the isolate with the introduction of a RxDart BehaviorSubject. Reading the current azimuth using await FlutterCompass.events.first will therefore not hang anymore when th user has not moved the handset at all.
  • Sample updated to cover the functional updates in Android.
  • Added missing locatio permissions to the Android example which prevented the permission dialog from being shown.

0.3.1 #

  • iOS: Remove permission request when Plugin is instantiated. Library users are responsible to request location permission by themselves.
  • Request permission in the example directly.

0.3.0 #

  • Replace kotlin code with simple java to reduce integration complexity

0.2.0 #

  • Upgrade Android build components (Kotlin version) Breaking change. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to also migrate if they're using the original support library.
  • Upgrade iOS component to Swift 4.2

0.1.0 #

  • Added example
  • Added public api docs

0.0.3 #

  • bug fixes

0.0.2 #

  • Android emulator fix

0.0.1 #

  • flutter compass plugin

example/lib/main.dart

import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:flutter_compass/flutter_compass.dart';
import 'package:permission_handler/permission_handler.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  const MyApp({
    Key key,
  }) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _hasPermissions = false;
  double _lastRead = 0;
  DateTime _lastReadAt;

  @override
  void initState() {
    super.initState();

    _fetchPermissionStatus();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('Flutter Compass'),
        ),
        body: Builder(builder: (context) {
          if (_hasPermissions) {
            return Column(
              children: <Widget>[
                _buildManualReader(),
                Expanded(child: _buildCompass()),
              ],
            );
          } else {
            return _buildPermissionSheet();
          }
        }),
      ),
    );
  }

  Widget _buildManualReader() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        children: <Widget>[
          RaisedButton(
            child: Text('Read Value'),
            onPressed: () async {
              final double tmp = await FlutterCompass.events.first;
              setState(() {
                _lastRead = tmp;
                _lastReadAt = DateTime.now();
              });
            },
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Text(
                  '$_lastRead',
                  style: Theme.of(context).textTheme.caption,
                ),
                Text(
                  '$_lastReadAt',
                  style: Theme.of(context).textTheme.caption,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCompass() {
    return StreamBuilder<double>(
      stream: FlutterCompass.events,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Text('Error reading heading: ${snapshot.error}');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: CircularProgressIndicator(),
          );
        }

        double direction = snapshot.data;

        // if direction is null, then device does not support this sensor
        // show error message
        if (direction == null)
          return Center(
            child: Text("Device does not have sensors !"),
          );

        return Container(
          alignment: Alignment.center,
          child: Transform.rotate(
            angle: ((direction ?? 0) * (math.pi / 180) * -1),
            child: Image.asset('assets/compass.jpg'),
          ),
        );
      },
    );
  }

  Widget _buildPermissionSheet() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Text('Location Permission Required'),
          RaisedButton(
            child: Text('Request Permissions'),
            onPressed: () {
              PermissionHandler().requestPermissions(
                  [PermissionGroup.locationWhenInUse]).then((ignored) {
                _fetchPermissionStatus();
              });
            },
          ),
          SizedBox(height: 16),
          RaisedButton(
            child: Text('Open App Settings'),
            onPressed: () {
              PermissionHandler().openAppSettings().then((opened) {
                //
              });
            },
          )
        ],
      ),
    );
  }

  void _fetchPermissionStatus() {
    PermissionHandler()
        .checkPermissionStatus(PermissionGroup.locationWhenInUse)
        .then((status) {
      if (mounted) {
        setState(() => _hasPermissions = status == PermissionStatus.granted);
      }
    });
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_compass: ^0.4.2+1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_compass/flutter_compass.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
93
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
96
Learn more about scoring.

We analyzed this package on Jul 2, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform linux

Because of import path [package:flutter_compass/flutter_compass.dart] that declares support for platforms: android, ios

Package does not support Flutter platform macos

Because of import path [package:flutter_compass/flutter_compass.dart] that declares support for platforms: android, ios

Package does not support Flutter platform web

Because of import path [package:flutter_compass/flutter_compass.dart] that declares support for platforms: android, ios

Package does not support Flutter platform windows

Because of import path [package:flutter_compass/flutter_compass.dart] that declares support for platforms: android, ios

Package not compatible with SDK dart

because of import path [flutter_compass] that is in a package requiring null.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.68.0 <3.0.0
flutter 0.0.0
rxdart ^0.24.0 0.24.1
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8