Flutter地理位置获取插件flutter_generic_location的使用
Flutter地理位置获取插件flutter_generic_location的使用
简介
flutter_generic_location
是一个用于在 Android 和 iOS 上获取前台和后台位置信息的 Flutter 插件。
支持的平台
- ✅ Android
- ✅ iOS
特性
- 可以请求位置权限。
- 可以获取设备的当前位置。
- 可以订阅
LocationStream
来实时收集位置数据。
开始使用
要使用此插件,请将其添加到项目的 pubspec.yaml
文件中作为依赖项。例如:
dependencies:
flutter_generic_location: ^0.0.1
平台特定配置
Android 配置
由于该插件基于位置服务工作,因此需要在 AndroidManifest.xml
文件中添加以下权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
如果需要在后台获取位置信息,请添加以下权限:
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
iOS 配置
与 Android 类似,iOS 平台也需要添加位置相关的描述信息。打开 ios/Runner/Info.plist
文件,并在 <dict>
标签内添加以下内容:
<key>NSLocationWhenInUseUsageDescription</key>
<string>Used to collect location data.</string>
如果需要在后台获取位置信息,请添加以下描述:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Used to collect location data in the background.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Used to collect location data in the background.</string>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>location</string>
</array>
使用示例
以下是一个完整的示例代码,展示了如何使用 flutter_generic_location
插件来获取位置信息并进行实时更新。
示例代码
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_generic_location/flutter_generic_location.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _flutterGenericLocationPlugin = FlutterGenericLocation();
late StreamSubscription<Map<String, dynamic>> streamSubscription;
bool runningLocationUpdates = false;
bool runningLocationService = false;
Map<String, dynamic> _location = {};
String _error = "";
[@override](/user/override)
void initState() {
super.initState();
// 订阅位置流以实时更新位置数据
streamSubscription = FlutterGenericLocation.locationStream.listen((location) {
setState(() {
_location = location;
});
});
}
// 获取当前位置
Future<void> getLocaion() async {
try {
final location = await _flutterGenericLocationPlugin.getLocation();
setState(() {
_location = location;
});
} catch (e) {
setState(() {
_error = e.toString();
});
}
}
// 获取最后的位置记录
Future<void> getLastLocation() async {
try {
final location = await _flutterGenericLocationPlugin.getLastLocation();
setState(() {
_location = location;
});
} catch (e) {
setState(() {
_error = e.toString();
});
}
}
// 启动或停止位置更新
Future<void> startStopLocationUpdates() async {
try {
if (runningLocationUpdates == false) {
await _flutterGenericLocationPlugin.startLocationUpdates();
runningLocationUpdates = true;
} else {
_flutterGenericLocationPlugin.stopLocationUpdates();
runningLocationUpdates = false;
}
setState(() {});
} catch (e) {
setState(() {
_error = e.toString();
});
}
}
// 启动或停止位置服务
Future<void> startAndStopLocaitonService() async {
try {
if (runningLocationService == false) {
await _flutterGenericLocationPlugin.startLocationService();
runningLocationService = true;
} else {
_flutterGenericLocationPlugin.stopLocationService();
runningLocationService = false;
}
setState(() {});
} catch (e) {
setState(() {
_error = e.toString();
});
}
}
// 获取通知图标
Future<Uint8List> fetchNotificationIcon() async {
ByteData imageData = await rootBundle.load('assets/images/notification_icon.png');
return imageData.buffer.asUint8List();
}
// 显示通知
Future<void> showNotification() async {
try {
final notificationIcon = await fetchNotificationIcon();
await _flutterGenericLocationPlugin.showNotification(
'Test Notification', 'This is a test notification message', "PluginDemoChannel", notificationIcon);
} catch (e) {
setState(() {
_error = e.toString();
});
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Generic Location Demo'),
),
body: Padding(
padding: const EdgeInsets.all(10.0),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// 显示位置信息
Text(
'Location Info on: $_location\n',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
// 显示错误信息
Text(
'Error: $_error\n',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
// 按钮:获取当前位置
ElevatedButton(
onPressed: () => getLocaion(),
child: const Text("Fetch Location"),
),
const SizedBox(height: 10),
// 按钮:获取最后的位置记录
ElevatedButton(
onPressed: () => getLastLocation(),
child: const Text("Fetch Last Location"),
),
const SizedBox(height: 10),
// 按钮:启动或停止位置更新
ElevatedButton(
onPressed: () => startStopLocationUpdates(),
child: runningLocationUpdates
? const Text("Stop Location Updates")
: const Text("Start Location Updates"),
),
const SizedBox(height: 10),
// 按钮:显示通知
ElevatedButton(
onPressed: () => showNotification(),
child: const Text("Show Notification"),
),
const SizedBox(height: 10),
// 按钮:启动或停止位置服务
ElevatedButton(
onPressed: () => startAndStopLocaitonService(),
child: runningLocationService
? const Text("Stop Location Service")
: const Text("Start Location Service"),
)
],
),
),
),
),
);
}
}
更多关于Flutter地理位置获取插件flutter_generic_location的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter地理位置获取插件flutter_generic_location的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
flutter_generic_location
是一个用于获取设备地理位置的 Flutter 插件。它提供了一个简单的方式来获取设备的经纬度、海拔、速度等信息。以下是如何使用 flutter_generic_location
插件的基本步骤:
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 flutter_generic_location
插件的依赖:
dependencies:
flutter:
sdk: flutter
flutter_generic_location: ^0.0.1 # 请使用最新版本
然后运行 flutter pub get
来安装依赖。
2. 导入包
在你的 Dart 文件中导入 flutter_generic_location
包:
import 'package:flutter_generic_location/flutter_generic_location.dart';
3. 获取地理位置
使用 FlutterGenericLocation
类来获取设备的地理位置。以下是一个简单的示例:
import 'package:flutter/material.dart';
import 'package:flutter_generic_location/flutter_generic_location.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LocationScreen(),
);
}
}
class LocationScreen extends StatefulWidget {
@override
_LocationScreenState createState() => _LocationScreenState();
}
class _LocationScreenState extends State<LocationScreen> {
String _locationInfo = 'Unknown';
Future<void> _getLocation() async {
try {
LocationData locationData = await FlutterGenericLocation.getLocation();
setState(() {
_locationInfo = 'Latitude: ${locationData.latitude}\n'
'Longitude: ${locationData.longitude}\n'
'Altitude: ${locationData.altitude}\n'
'Speed: ${locationData.speed}';
});
} catch (e) {
setState(() {
_locationInfo = 'Failed to get location: $e';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Location Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_locationInfo),
SizedBox(height: 20),
ElevatedButton(
onPressed: _getLocation,
child: Text('Get Location'),
),
],
),
),
);
}
}
4. 处理权限
在 Android 和 iOS 上,获取地理位置需要相应的权限。确保在 AndroidManifest.xml
和 Info.plist
文件中添加必要的权限。
Android
在 AndroidManifest.xml
中添加以下权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
iOS
在 Info.plist
中添加以下键值对:
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to show it on the map.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>We need your location to show it on the map.</string>