Не определяются текущие координаты при импорте пакета geolocator во Flutter

Изучаю новую для себя тему: Мобильная разработка и как учебный проект работаю над приложением, которое будет использовать геолокацию пользователя, но столкнулся с тем, что приложение работает не так как ожидал, местоположение отказывается определяться. Прошу помощи у знающих людей, что не так? Либо я этот геолокатор не так подключил, хотя следовал инструкциям, либо накосячил с кодом, что более вероятно, но опять таки не пойму где. Окружение, на котором пытаюсь запустить приложение Pixel 8, API: TiramisuPrivacySandbox, Type: Virtual,

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:spot_the_bird/bloc/location_cubit.dart';
import 'package:spot_the_bird/screens/map_screen.dart';

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return
      BlocProvider<LocationCubit>(
        create: (context) => LocationCubit()..getLocation(),
        child: MaterialApp(
        theme: ThemeData(
          primaryColor: Color(0xFF334257),
          colorScheme: ColorScheme.light().copyWith(
            primary: Color(0xFF548CAB),
            secondary: Color(0xFF96BAFF),
          ),
          // useMaterial3: true,
        ),
        home: MapScreen(),
            ),
      );
  }

Сам экран приложения map_screen.dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:spot_the_bird/bloc/location_cubit.dart';

class MapScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocBuilder<LocationCubit, LocationState>(
        builder: (context, state){
          if(state is LocationLoaded){
            return FlutterMap(
                options: MapOptions(
                  initialCenter: LatLng(state.latitude, state.longitude), // Center the map over London
                  initialZoom: 8.3,
                  maxZoom: 17,
                  minZoom: 3.5,
                ),
                children: [
                  TileLayer( // Display map tiles from any source
                    urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', // OSMF's Tile Server
                    userAgentPackageName: 'com.example.app',
                    // And many more recommended properties!
                    subdomains: ['a', 'b', 'c'],
                    retinaMode: true,
                  ),
                ]
            );
          }
          if(state is LocationError){
            Center(child: MaterialButton(child: Text("Try Again"),
              onPressed: (){
                context.read<LocationCubit>().getLocation();
              },
            )
            );
          }
          return Center(child:CircularProgressIndicator());
        },
      ),
    );
  }
}

Дальше два файла логики кубит location_cubit.dart - для бизнес логики

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:geolocator/geolocator.dart';
part 'location_state.dart';

class LocationCubit extends Cubit<LocationState>{
  LocationCubit(): super(LocationInitial());

  Future<void> getLocation() async{
    LocationPermission permission = await Geolocator.checkPermission();

    if(permission != LocationPermission.denied || permission != LocationPermission.deniedForever){
      emit(LocationLoading());
       try{
         final LocationSettings locationSettings = LocationSettings(
           accuracy: LocationAccuracy.high,
           distanceFilter: 100,
         );

         Position position = await Geolocator.getCurrentPosition(locationSettings: locationSettings);
         emit(LocationLoaded(latitude: position.latitude, longitude: position.longitude));
       }catch(error){
         print(error.toString());
         emit(LocationError());
       }
    }
  }
}

И location_state.dart для отображения UI

part of 'location_cubit.dart';

abstract class LocationState extends Equatable{
  const LocationState();

  @override
  List<Object> get props => [];
}

class LocationInitial extends LocationState{
  const LocationInitial();
}

class LocationLoading extends LocationState{
  const LocationLoading();
}

class LocationError extends LocationState{
  const LocationError();
}

class LocationLoaded extends LocationState{
  final double latitude;
  final double longitude;

  const LocationLoaded({required this.latitude, required this.longitude});

  @override
  List<Object> get props => [latitude, longitude];
}

в pubspec.yaml также всё подключил, но latlong2 и geolocator подчёркнуты зелёным, но при команде pub get получаю код 0

dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.8
  flutter_map: ^7.0.2
  latlong2: ^0.9.1
  geolocator: ^13.0.1
  bloc: ^8.1.4
  flutter_bloc: ^8.1.6
  equatable: ^2.0.5

Если надо что-то ещё дополнительно скинуть с папки Андроид - пишите скину


Ответы (0 шт):