本文档以一个最小可运行示例展示如何完成 SDK 初始化、申请系统权限、获取一次定位结果并释放资源的完整流程。
阅读本文档之前,请先完成 集成 Flutter 插件 与 隐私合规接口 中描述的工程配置。
下面这段代码可以直接放在你的 main.dart 中运行。在真机上首次运行时,系统会弹出权限申请对话框,授权后即可看到打印的定位结果。
import 'package:flutter/material.dart';
import 'package:tencent_location_flutter_plugin/tencent_location_flutter_plugin.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// 第一步:用户同意隐私政策(在你的应用展示隐私弹窗并获得用户同意之后调用)。
await TencentLocationSDK.setPrivacyPolicyAgreement(true);
// 第二步:用申请到的 ApiKey 初始化 SDK。
await TencentLocationSDK.init(
androidApiKey: 'YOUR_ANDROID_API_KEY',
iosApiKey: 'YOUR_IOS_API_KEY',
);
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _result = '点击按钮发起单次定位';
Future<void> _requestLocation() async {
final manager = TencentLocationManager();
try {
// iOS 在首次定位前需要申请系统权限。
// Android 端请按运行时权限规则单独申请 ACCESS_FINE_LOCATION / ACCESS_COARSE_LOCATION。
await TencentLocationSDK.requestIosWhenInUseAuthorization();
final request = TencentLocationRequest.create()
..setRequestLevel(RequestLevel.adminArea)
..setCoordinateType(CoordinateType.gcj02);
final location = await manager.startSingleLocation(request);
setState(() {
_result = '定位成功:${location.latitude}, ${location.longitude}\n'
'地址:${location.geoAddress?.address ?? '无'}';
});
} on TencentLocationError catch (error) {
setState(() {
_result = '定位失败:${error.code} ${error.message}';
});
} finally {
await manager.dispose();
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('腾讯定位 Flutter 插件示例')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(_result, textAlign: TextAlign.center),
),
ElevatedButton(
onPressed: _requestLocation,
child: const Text('单次定位'),
),
],
),
),
),
);
}
}
任何插件方法被调用之前都必须先执行 TencentLocationSDK.setPrivacyPolicyAgreement(true),否则会得到 privacyNotAgreed 错误。详细说明见 隐私合规接口。
TencentLocationSDK.init 接受 Android 与 iOS 的 ApiKey,分别用于对应平台。如果你的应用只面向其中一个平台,另一端的 ApiKey 可以省略。
iOS 端通过 requestIosWhenInUseAuthorization() 触发系统权限弹窗。
Android 端的运行时权限申请由 Flutter 应用自身负责(可使用 permission_handler 等社区插件,或编写原生代码),插件不会代为请求。
每次定位前创建一个 TencentLocationManager 实例,发起请求并等待结果,使用完毕后调用 dispose() 释放。多次连续定位场景请见 连续定位。
所有插件方法在原生侧失败时都会抛出 TencentLocationError,建议使用 try / on 捕获并将 code 与 message 上报到你的日志系统,便于问题排查。完整错误码列表见 错误码。
有帮助
没帮助