ActivityMissingException с использованием requestPermission() Geolocator даже с WidgetsBinding.instance.addPostFrameCallAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 ActivityMissingException с использованием requestPermission() Geolocator даже с WidgetsBinding.instance.addPostFrameCall

Сообщение Anonymous »

Я получаю исключение ActivityMissingException при запросе разрешений на определение местоположения с помощью плагина Geolocator во Flutter:

Код: Выделить всё

ActivityMissingException (Activity is missing. This might happen when running a certain function from the background that requires a UI element (e.g. requesting permissions or enabling the location services).)
Ошибка возникает в этой строке:

Код: Выделить всё

permission = await _geolocatorPlatform.requestPermission();
Где Final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;
Я пробовал:
  • Использование WidgetsBinding.instance.addPostFrameCallback (показано ниже)
  • Добавление Future.delayed с различными задержками (до 10 секунд, всё точно загрузилось)
  • Проверка context.mounted перед запросами (показано ниже)
  • Перенос запроса разрешения на первую сборку с помощью Future .microtask
Моя текущая реализация функции initState в виджете главной страницы:

Код: Выделить всё

@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
handleLocationPermission(context);
}
});
}
Моя текущая реализация функции handleLocationPermission:

Код: Выделить всё

Future handleLocationPermission(BuildContext context) async {
if (!context.mounted) return;

bool serviceEnabled;
LocationPermission permission;
LocationAccuracyStatus accuracy;

// Test if location services are enabled.
serviceEnabled = await _geolocatorPlatform.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.
if (!context.mounted) return;
showAlert(context,
title: locationDisabledAlertTitle,
text1: locationDisabledAlertText1,
text2: locationDisabledAlertText2,
doNothingActionText: "Ok",
doSomethingActionText: "Open Settings", onDoSomething: () {
_geolocatorPlatform.openLocationSettings();
});
return;
}

// Test if permissions are given. If not, request permission.
permission = await _geolocatorPlatform.checkPermission();
if (!context.mounted) return; // Added these extra mount checks
if (permission == LocationPermission.denied) {
permission = await _geolocatorPlatform.requestPermission(); // Fails here
}
...
Flutter Doctor (проблем не обнаружено):

Код: Выделить всё

[✓] Flutter (Channel stable, 3.24.3, on macOS 15.1 24B83 darwin-arm64, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 35.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 16.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2024.1)
[✓] VS Code (version 1.95.1)
[✓] Connected device (5 available)
[✓] Network resources
Среда:
  • Версия плагина геолокатора: 12.0.0
  • Платформа : Pixel 6 Android 14 (API 34)
Как правильно запросить разрешения на определение местоположения, не получая ActivityMissingException?

Подробнее здесь: https://stackoverflow.com/questions/791 ... ith-widget
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»