본문 바로가기

dev/flutter

geolocator

기기 위치 가져오기 라이브러리를 이용해 현재 위치를 구한다.

 

 

geolocator | Flutter Package

Geolocation plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API for generic location (GPS etc.) functions.

pub.dev

geolocator 를 설치한다.

flutter pub add geolocator

버전이 낮으면 이러한 오류가 뜬다.

 

flutter upgrade 명령어로 dart 와 flutter 를 업그레이드 해준다.

IOS 와 안드로이드 모두 위치 권한이 필요하다.

 

안드로이드

AndroidManifest 파일에 위치 권한을 추가해준다.

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

gradle.properties 에 AndroidX, Jetifier 사용 여부를 확인한다.

AndroidX : 기존의 Android support library가 대체되어진 것이다.

Jetifier : Android support library 에서 AndroidX 로 마이그레이션될 때 필요하다.

 

IOS

info.plist 파일에 권한을 추가한다.

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in the background.</string>

 

location사용과 권한 체크를 해주고 현재 위치를 반환하는 함수를 넣는다.

 

 

버튼을 클릭하면 현재 위치가 로그에 뜬다.

 

 

import 'dart:developer';

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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


  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  String currentPosition = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                await _determinePosition().then((value) {
                  currentPosition = value.toString();
                  log(currentPosition);
                });
              }, 
              child: Text("start")
            )
          ],
        ),
      ),
    );
  }
}

Future<Position> _determinePosition() async {
  bool serviceEnabled;
  LocationPermission permission;

  // Test if location services are enabled.
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    // Location services are not enabled don't continue
    // accessing the position and request users of the 
    // App to enable the location services.
    return Future.error('Location services are disabled.');
  }

  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      // Permissions are denied, next time you could try
      // requesting permissions again (this is also where
      // Android's shouldShowRequestPermissionRationale 
      // returned true. According to Android guidelines
      // your App should show an explanatory UI now.
      return Future.error('Location permissions are denied');
    }
  }
  
  if (permission == LocationPermission.deniedForever) {
    // Permissions are denied forever, handle appropriately. 
    return Future.error(
      'Location permissions are permanently denied, we cannot request permissions.');
  } 

  // When we reach here, permissions are granted and we can
  // continue accessing the position of the device.
  return await Geolocator.getCurrentPosition();
}

'dev > flutter' 카테고리의 다른 글

statusbar 뒤에 이미지 넣기  (0) 2023.01.25
권한  (0) 2023.01.25
[movie_app] 개봉 예정 영화  (0) 2023.01.10
[movie_app] 상세페이지  (0) 2023.01.08
[movie_app] 네이버 영화 검색 API  (0) 2023.01.08