Flutter - Detect Fake GPS Mock Location Examples

This tutorial shows you how to detect if the device that runs a Flutter application can mock the location, also known as fake GPS.

Modern devices have a feature for getting the current location using GPS. However, sometimes some users may change the actual location to another one that they want. In some cases, we may restrict an application or a feature to only be used by users that use their real location. As a result, we need a way to detect whether the device can mock the location or not.

Using safe_device

There's a package that makes it easier to do that. You can add safe_device as a dependency.

  flutter pub add safe_device

Then, you can use it in your code by adding the import statement below.

  import 'package:safe_device/safe_device.dart';

The package has a class named SafeDevice which has a getter named canMockLocation. The getter returns Future<bool>. If the return value is true, it means the location can be mocked. On Android, it checks whether the device's location can be mocked. On iOS, it checks whether the device is jailbroken. The method may also return true if the application is running on a non-real device such as an emulator. Below is the usage example.

  Future<bool> _canMockLocation() async {
    bool canMockLocation = await SafeDevice.canMockLocation;
    return canMockLocation;
  }

Full Code

Below is the full code of this tutorial that displays the result in a Text widget. Since the method above returns a Future, we can use a FutureBuilder to build the Text widget.

  import 'package:flutter/material.dart';
  import 'package:safe_device/safe_device.dart';
  
  void main() => runApp(const MyApp());
  
  class MyApp extends StatelessWidget {
  
    const MyApp({super.key});
  
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Woolha.com Flutter Tutorial',
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Woolha.com Flutter Tutorial'),
            backgroundColor: Colors.teal,
          ),
          body: const MyPage(),
        ),
      );
    }
  }
  
  class MyPage extends StatelessWidget {
    const MyPage({super.key});
  
    Future<bool> _canMockLocation() async {
      bool canMockLocation = await SafeDevice.canMockLocation;
      return canMockLocation;
    }
  
    @override
    Widget build(BuildContext context) {
      return Center(
        child: FutureBuilder(
          future: _canMockLocation(),
          builder: (context, AsyncSnapshot<bool> snapshot) {
            return Text(snapshot.hasData ? '${snapshot.data}' : '-');
          },
        ),
      );
    }
  }

Summary

To check whether the device can mock location can be done by using the safe_device package. You just need to add the package and call the getter method.

You can also read about: