Flutter位置打卡插件junny_location_punch的使用

Flutter位置打卡插件junny_location_punch的使用

Features

这是为项目抽取的定位打卡功能库。目前定位功能使用高德。

Getting started

Android

android/src/main/AndroidManifest.xml 文件中添加以下内容:

<manifest>
    <application>
        /// 需要配置的
        <meta-data android:name="com.amap.api.v2.apikey" android:value="您的Key" />
    </application>
</manifest>
iOS
  1. Info.plist 中增加:
<key>NSLocationWhenInUseUsageDescription</key>
<string>要用定位</string>

如果iOS定位没有返回逆地理信息,添加以下内容:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSAllowsArbitraryLoadsForMedia</key>
    <true/>
    <key>NSAllowsArbitraryLoadsInWebContent</key>
    <true/>
    /// 解决ios HTTP 警告,需要添加的
    <key>NSExceptionDomains</key>
    <dict>
        <key>restios.amap.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
        </dict>
    </dict>
</dict>
  1. iOS 9及以上版本使用后台定位功能,需要保证"Background Modes"中的"Location updates"处于选中状态。

  2. 使用地理围栏

iOS14及以上版本使用地理围栏功能,需要在 Info.plist 中配置 NSLocationTemporaryUsageDescriptionDictionary 字典描述,并添加自定义Key描述地理围栏的使用场景。此描述会在申请临时精确定位权限的弹窗中展示。该回调触发条件:拥有定位权限,但是没有获得精确定位权限的情况下,会触发该回调。此方法实现调用申请临时精确定位权限API即可。

**需要注意,在iOS9及之后版本的系统中,如果您希望程序在后台持续检测围栏触发行为,需要保证manager的 allowsBackgroundLocationUpdatesYES,设置为 YES 的时候必须保证 “Background Modes” 中的 “Location updates” 处于选中状态,否则会抛出异常。

完整示例代码

以下是使用 junny_location_punch 插件的完整示例代码:

import 'package:flutter/material.dart';
import 'package:junny_location_punch/junny_location_punch.dart'; // 导入位置打卡插件

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  // 初始化定位插件
  late JunnyLocationPunch junnyLocationPunch;

  [@override](/user/override)
  void initState() {
    super.initState();
    junnyLocationPunch = JunnyLocationPunch(); // 创建定位插件实例
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  // 打卡函数
  Future<void> punchIn() async {
    try {
      var result = await junnyLocationPunch.punchIn(); // 执行打卡操作
      print('打卡结果: $result');
    } catch (e) {
      print('打卡失败: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _incrementCounter();
          punchIn(); // 点击按钮时进行打卡操作
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter位置打卡插件junny_location_punch的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


junny_location_punch 是一个用于在 Flutter 应用中实现位置打卡功能的插件。它可以帮助开发者轻松地获取用户的地理位置,并在特定位置进行打卡操作。以下是如何在 Flutter 项目中使用 junny_location_punch 插件的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 junny_location_punch 插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  junny_location_punch: ^1.0.0  # 请使用最新版本

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

2. 获取用户位置权限

在使用 junny_location_punch 之前,你需要确保你的应用已经获取了用户的位置权限。你可以在 AndroidManifest.xmlInfo.plist 文件中添加相应的权限声明。

Android

android/app/src/main/AndroidManifest.xml 中添加以下权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

iOS

ios/Runner/Info.plist 中添加以下权限:

<key>NSLocationWhenInUseUsageDescription</key>
<string>我们需要您的位置信息来提供打卡服务。</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>我们需要您的位置信息来提供打卡服务。</string>

3. 初始化插件

在你的 Dart 代码中,初始化 junny_location_punch 插件。

import 'package:junny_location_punch/junny_location_punch.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: LocationPunchScreen(),
    );
  }
}

4. 获取当前位置并打卡

你可以使用 JunnyLocationPunch 类来获取用户的地理位置,并在特定位置进行打卡。

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

class LocationPunchScreen extends StatefulWidget {
  [@override](/user/override)
  _LocationPunchScreenState createState() => _LocationPunchScreenState();
}

class _LocationPunchScreenState extends State<LocationPunchScreen> {
  String _locationStatus = '未打卡';

  Future<void> _punchLocation() async {
    try {
      // 获取当前位置
      final location = await JunnyLocationPunch.getCurrentLocation();

      // 假设打卡位置为某个固定坐标
      final punchLocation = Location(latitude: 39.9042, longitude: 116.4074);

      // 判断是否在打卡范围内
      final isInRange = await JunnyLocationPunch.isInRange(
        currentLocation: location,
        targetLocation: punchLocation,
        radius: 100, // 打卡范围半径,单位为米
      );

      if (isInRange) {
        setState(() {
          _locationStatus = '打卡成功';
        });
      } else {
        setState(() {
          _locationStatus = '不在打卡范围内';
        });
      }
    } catch (e) {
      setState(() {
        _locationStatus = '打卡失败: $e';
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('位置打卡'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('打卡状态: $_locationStatus'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _punchLocation,
              child: Text('打卡'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部