构件flutter定位服务

简介: 在本教程中,我将向您展示如何从服务中获取您在 Flutter 中的位置。在 Flutter 中获取您的位置是一项简单的任务。本教程将向您展示如何将位置包包装到易于在您的应用程序中使用的服务中。创建一个新的 Flutter 项目并继续。

在本教程中,我将向您展示如何从服务中获取您在 Flutter 中的位置。

在 Flutter 中获取您的位置是一项简单的任务。本教程将向您展示如何将位置包包装到易于在您的应用程序中使用的服务中。创建一个新的 Flutter 项目并继续。

设置

Provider 是我的默认依赖提供者/状态管理解决方案,所以我们也将使用它。我们将这两个包添加到 pubspec.yaml 文件中。

provider: ^3.0.0
location: ^2.3.5
复制代码

安卓

将位置权限添加到AndroidManifest.xml应用程序标签之外的清单中。

...
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="The Guardian"
        android:icon="@mipmap/ic_launcher">
        ...
    </application>
...
复制代码

将您的 gradle.properties 文件更新为此

android.enableJetifier=true
android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536M
复制代码

将您的 build.gradle 文件依赖项更新为此

dependencies {
      classpath 'com.android.tools.build:gradle:3.3.0'
      classpath 'com.google.gms:google-services:4.2.0'
  }
复制代码

并确保您compileSdkVersion是 28 。

IOS

<key>NSLocationWhenInUseUsageDescription</key>
    <string>This app requires access to your location for FilledStacks tutorial.</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>This app requires access to your location for FilledStacks tutorial.</string>
复制代码

这就是所有设置完成。如果您遇到 AndroidX 问题,请确保迁移或使用此软件包的旧版本(如果您不想迁移)。

服务实施

如果有一件事我可以推荐,那就是阅读单一职责原则。基于此,我养成了使用单一用途服务构建应用程序的习惯,这些服务在需要时注入/定位。让我们创建我们的LocationService. 这项服务将:

  1. 提供我们可以依赖的持续更新流
  2. 提供对当前位置执行一次性请求的函数

在 services 文件夹下创建一个名为 location_service.dart 的新文件。我们将首先添加getLocation()可用于一次性检索的单一请求函数。

import 'package:location/location.dart';
class LocationService {
  UserLocation _currentLocation;
  var location = Location();
  Future<UserLocation> getLocation() async {
    try {
      var userLocation = await location.getLocation();
      _currentLocation = UserLocation(
        latitude: userLocation.latitude,
        longitude: userLocation.longitude,
      );
    } on Exception catch (e) {
      print('Could not get location: ${e.toString()}');
    }
    return _currentLocation;
  }
}
复制代码

我们还将引入我们自己的 Location 模型,以确保我们的外部代码不依赖于模型的包表示。在模型文件夹下创建一个名为 user_location.dart 的新文件

class UserLocation {
  final double latitude;
  final double longitude;
  UserLocation({this.latitude, this.longitude});
}
复制代码

现在让我们添加向我们发出所有用户位置更新的 Stream。下面的所有代码都在定位服务中。

StreamController<UserLocation> _locationController =
      StreamController<UserLocation>();
  Stream<UserLocation> get locationStream => _locationController.stream;
  LocationService() {
    // Request permission to use location
    location.requestPermission().then((granted) {
      if (granted) {
        // If granted listen to the onLocationChanged stream and emit over our controller
        location.onLocationChanged().listen((locationData) {
          if (locationData != null) {
            _locationController.add(UserLocation(
              latitude: locationData.latitude,
              longitude: locationData.longitude,
            ));
          }
        });
      }
    });
  }
复制代码

此服务旨在用于控制视图状态和处理逻辑的对象,而不是视图本身。话虽如此,为了保持本教程的简短和范围,我只会将流传递给提供者以展示我们如何使用它。我们将使用 StreamProvider 包装主应用程序,并从 LocationService 向构建器提供流。

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return StreamProvider<UserLocation>(
      builder: (context) => LocationService().locationStream,
      child: MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            body: HomeView(),
          )),
    );
  }
}
复制代码

然后HomeView我们将使用该流并打印出位置值。

class HomeView extends StatelessWidget {
  const HomeView({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    var userLocation = Provider.of<UserLocation>(context);
    return Center(
      child: Text(
          'Location: Lat${userLocation?.latitude}, Long: ${userLocation?.longitude}'),
    );
  }
}



相关文章
|
16天前
|
Android开发 iOS开发 容器
鸿蒙harmonyos next flutter混合开发之开发FFI plugin
鸿蒙harmonyos next flutter混合开发之开发FFI plugin
|
4月前
|
开发框架 前端开发 测试技术
Flutter开发常见问题解答
Flutter开发常见问题解答
|
5天前
|
开发者
鸿蒙Flutter实战:07-混合开发
鸿蒙Flutter混合开发支持两种模式:1) 基于har包,便于主项目开发者无需关心Flutter细节,但不支持热重载;2) 基于源码依赖,利于代码维护与热重载,需配置Flutter环境。项目结构包括AppScope、flutter_module等目录,适用于不同开发需求。
19 3
|
26天前
|
开发框架 移动开发 Android开发
安卓与iOS开发中的跨平台解决方案:Flutter入门
【9月更文挑战第30天】在移动应用开发的广阔舞台上,安卓和iOS两大操作系统各自占据半壁江山。开发者们常常面临着选择:是专注于单一平台深耕细作,还是寻找一种能够横跨两大系统的开发方案?Flutter,作为一种新兴的跨平台UI工具包,正以其现代、响应式的特点赢得开发者的青睐。本文将带你一探究竟,从Flutter的基础概念到实战应用,深入浅出地介绍这一技术的魅力所在。
65 7
|
5天前
|
编解码 Dart API
鸿蒙Flutter实战:06-使用ArkTs开发Flutter鸿蒙插件
本文介绍了如何开发一个 Flutter 鸿蒙插件,实现 Flutter 与鸿蒙的混合开发及双端消息通信。通过定义 `MethodChannel` 实现 Flutter 侧的 token 存取方法,并在鸿蒙侧编写 `EntryAbility` 和 `ForestPlugin`,使用鸿蒙的首选项 API 完成数据的读写操作。文章还提供了注意事项和参考资料,帮助开发者更好地理解和实现这一过程。
23 0
|
5天前
|
Dart Android开发
鸿蒙Flutter实战:03-鸿蒙Flutter开发中集成Webview
本文介绍了在OpenHarmony平台上集成WebView的两种方法:一是使用第三方库`flutter_inappwebview`,通过配置pubspec.lock文件实现;二是编写原生ArkTS代码,自定义PlatformView,涉及创建入口能力、注册视图工厂、处理方法调用及页面构建等步骤。
10 0
|
5月前
|
前端开发 C++ 容器
Flutter-完整开发实战详解(一、Dart-语言和-Flutter-基础)(1)
Flutter-完整开发实战详解(一、Dart-语言和-Flutter-基础)(1)
|
1月前
|
JSON Dart Java
flutter开发多端平台应用的探索
flutter开发多端平台应用的探索
44 6
|
1月前
|
JSON Dart Java
flutter开发多端平台应用的探索 下 (跨模块、跨语言通信之平台通道)
flutter开发多端平台应用的探索 下 (跨模块、跨语言通信之平台通道)
|
1月前
|
安全 Android开发 开发者
探索安卓开发的未来:Kotlin的崛起与Flutter的挑战
在移动开发的广阔天地中,安卓平台始终占据着举足轻重的地位。随着技术的不断进步和开发者需求的多样化,Kotlin和Flutter成为了改变游戏规则的新玩家。本文将深入探讨Kotlin如何以其现代化的特性赢得开发者的青睐,以及Flutter凭借跨平台的能力如何挑战传统的安卓开发模式。通过实际案例分析,我们将揭示这两种技术如何塑造未来的安卓应用开发。
64 6