Flutter实时位置追踪插件hypertrack_plugin的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter HyperTrack SDK

HyperTrack allows you to add live location tracking to your mobile app. Live location is made available along with ongoing activity, tracking controls, and tracking outage with reasons.

Flutter HyperTrack SDK is a wrapper around native iOS and Android SDKs that allows integration of HyperTrack into Flutter apps. For detailed instructions on how to get started, check this Guide.

Installation

To add the hypertrack_plugin to your Flutter project, run the following command:

flutter pub add hypertrack_plugin

Sample Code

You can find a quickstart Flutter app example here.

Wrapper API Documentation

For more details about the API, refer to the Wrapper API Documentation.

Requirements

Android

  • Gradle version 6.7.1+
  • compileSdkVersion 31+

iOS

  • iOS version 12.4+

Contributing

If you wish to contribute to the project, please check the CONTRIBUTING.md.

Complete Example Demo

Below is a simple example demonstrating how to use the hypertrack_plugin for real-time location tracking in a Flutter application.

main.dart

import 'package:flutter/material.dart';
import 'package:hypertrack_plugin/hypertrack.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'HyperTrack Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'HyperTrack Real-Time Location Tracking'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  String _deviceId = '';

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

  Future<void> _initializeHyperTrack() async {
    // Initialize HyperTrack with your Publishable Key
    await HyperTrack.initialize('YOUR_PUBLISHABLE_KEY');
    
    // Get Device ID
    var device = await HyperTrack.getDeviceId();
    setState(() {
      _deviceId = device;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Your Device ID:',
            ),
            Text(
              '$_deviceId',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // Start tracking
          await HyperTrack.startTracking();
        },
        tooltip: 'Start Tracking',
        child: Icon(Icons.play_arrow),
      ),
    );
  }
}

Notes:

  • Replace 'YOUR_PUBLISHABLE_KEY' with your actual HyperTrack publishable key.
  • Ensure you have added necessary permissions in AndroidManifest.xml and Info.plist for accessing location services.

This demo provides a basic setup to start using HyperTrack’s real-time location tracking features in a Flutter application. For more advanced usage, refer to the official documentation and sample code provided by HyperTrack.


更多关于Flutter实时位置追踪插件hypertrack_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter实时位置追踪插件hypertrack_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter应用中使用hypertrack_plugin进行实时位置追踪的代码示例。这个插件允许你集成Hypertrack的SDK,以实现实时位置追踪功能。

首先,确保你已经在pubspec.yaml文件中添加了hypertrack_plugin依赖:

dependencies:
  flutter:
    sdk: flutter
  hypertrack_plugin: ^最新版本号  # 请替换为实际的最新版本号

然后,运行flutter pub get来安装依赖。

接下来,你需要按照Hypertrack的文档完成SDK的初始化设置,包括获取API密钥和配置应用权限(如位置权限)。

初始化Hypertrack

在你的Flutter应用的入口文件(通常是main.dart)中,进行Hypertrack的初始化:

import 'package:flutter/material.dart';
import 'package:hypertrack_plugin/hypertrack_plugin.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化Hypertrack
  await HypertrackPlugin.init(
    apiKey: 'YOUR_HYPERTRACK_API_KEY',  // 替换为你的Hypertrack API密钥
    debug: true,  // 设置为true用于调试,生产环境应设置为false
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

开始位置追踪

在你的主页面或需要开始位置追踪的地方,调用Hypertrack的startTracking方法:

import 'package:flutter/material.dart';
import 'package:hypertrack_plugin/hypertrack_plugin.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();

    // 开始位置追踪
    _startTracking();
  }

  Future<void> _startTracking() async {
    try {
      await HypertrackPlugin.startTracking(
        userId: 'USER_ID',  // 替换为用户的唯一标识符
        metadata: {'key': 'value'},  // 可选的元数据
      );
      print('Tracking started successfully');
    } catch (e) {
      print('Error starting tracking: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Real-time Location Tracking'),
      ),
      body: Center(
        child: Text('Tracking is started'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // 停止位置追踪
          await HypertrackPlugin.stopTracking();
          print('Tracking stopped');
        },
        tooltip: 'Stop Tracking',
        child: Icon(Icons.stop),
      ),
    );
  }
}

处理位置更新

为了处理位置更新,你可以监听Hypertrack提供的位置流。这通常需要在你的应用中设置一个监听器来接收位置更新。

import 'package:flutter/material.dart';
import 'package:hypertrack_plugin/hypertrack_plugin.dart';

class _MyHomePageState extends State<MyHomePage> {
  StreamSubscription<Map<String, dynamic>>? _locationSubscription;

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

    _startTracking();

    // 监听位置更新
    _locationSubscription = HypertrackPlugin.onLocationUpdate().listen((location) {
      print('Location update: $location');
      // 在这里处理位置更新,例如更新UI
    });
  }

  @override
  void dispose() {
    // 取消订阅位置更新流
    _locationSubscription?.cancel();
    _locationSubscription = null;

    // 停止位置追踪(可选,如果已经在其他地方停止)
    // HypertrackPlugin.stopTracking();

    super.dispose();
  }

  // ... 其他代码,如_startTracking方法
}

这个示例展示了如何在Flutter应用中使用hypertrack_plugin进行实时位置追踪的基本步骤。请确保你遵循Hypertrack的文档和最佳实践,以充分利用其功能并确保应用的稳定性和安全性。

回到顶部