Khám phá công nghệ

Khám phá các công cụ và kỹ thuật hữu ich cho Lập trình viên

Hướng dẫn sử dụng location package trong Flutter

Thắng Nguyễn

Thu, 02 May 2024

Hướng dẫn sử dụng location package trong Flutter

Bài viết này sẽ hướng dẫn bạn sử dụng location package trở thành một dịch vụ dễ sử dụng trong ứng dụng Flutter. Hãy bắt đầu bằng cách tạo một dự án Flutter mới và tiến hành theo hướng dẫn dưới đây.

Cài đặt

Dự án này sử dụng Provider là trình quản lý trạng thái, vì vậy chúng ta sẽ bổ sung các gói vào pubspec.yaml

provider: ^3.0.0
location: ^2.3.5

Android

Thêm quyền truy cập vị trí vào AndroidManifest.xml bên ngoài thẻ application

...
    <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>
...

Cập nhật tệp gradle.properties.

android.enableJetifier=true
android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536M

Cập nhật phụ thuộc trong tệp build.gradle.

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

Đảm bảo compileSdkVersion của bạn là 28.

iOS

Thêm quyền vị trí vào info.plist với các thông báo phù hợp.

<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>

Triển khai dịch vụ

Tạo một dịch vụ Location để cung cấp dữ liệu vị trí.

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;
  }
}

Tạo một model mới để đại diện cho vị trí người dùng.

class UserLocation {
  final double latitude;
  final double longitude;

  UserLocation({this.latitude, this.longitude});
}

Thêm Stream để phát các cập nhật vị trí người dùng

 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,
            ));
          }
        });
      }
    });
  }

Sử dụng dịch vụ

Wrap main app với StreamProvider và cung cấp stream từ 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(),
          )),
    );
  }
}

Tiếp theo, trong HomeView, hiển thị giá trị vị trí.

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}'),
    );
  }
}

Đó là một cái nhìn tổng quan về cách triển khai và sử dụng dịch vụ vị trí trong Flutter.

0 Comments

Để lại một bình luận