使用geolocator和provider和flutter_maps获取位置

问题描述 投票:1回答:1

我正在尝试通过geolocator插件获取用户的当前位置,并且我正在使用提供程序包来处理状态。但是我收到“初始位置为null”错误消息。我使用的是flutter_maps软件包,而不是Google地图。

我试图使用提供程序包寻找解决方案,但没有找到。

这是我的代码:

main.dart:

import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import './maps_module/map_states.dart';
import 'home_page.dart';


void main() {
  WidgetsFlutterBinding.ensureInitialized();
  return runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: AppState())
      ],
      child: MyApp(),
    )
  );
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

home_page.dart:

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

import './maps_module/map_states.dart';
import './maps_module/maps_screen.dart';


class HomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    final appState = Provider.of<AppState>(context);

    return Scaffold(
      body: appState.initialPosition == null?
      Center(
        child: CircularProgressIndicator(),
      )
      :MapScreen(),
    );
  }
}

map_screen.dart:

import 'package:flutter/material.dart';

import 'package:provider/provider.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong/latlong.dart';

import 'map_states.dart';


class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => new _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {

  @override
  Widget build(BuildContext context) {

    final appState = Provider.of<AppState>(context);

    return SafeArea(
      child: Scaffold(
        // appBar: AppBar(),
        body: FlutterMap(
          mapController: appState.mapController,
          options: MapOptions(
            center: LatLng(appState.initialPosition.latitude, appState.initialPosition.longitude),
            minZoom: 10.0
          ),
          layers: [
            TileLayerOptions(
              urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
              subdomains: ['a','b','c']
            ),
            MarkerLayerOptions(
              markers: [
                Marker(
                  width: 80.0,
                  height: 80.0,
                  point: appState.initialPosition,
                  builder: (context) =>
                  Container(
                    child: IconButton(
                      icon: Icon(Icons.location_on),
                      color: Colors.redAccent,
                      iconSize: 45.0,
                      onPressed: (){print("hey");}
                    ),
                  )
                )
              ]
            )
          ],
        ),
      )
    );
  }
}

地图状态:

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

import 'package:flutter_map/flutter_map.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong/latlong.dart';


class AppState with ChangeNotifier {

  bool locationServiceActive = true;

  MapController _mapController;
  MapController get mapController => _mapController;

  static var _initialPosition;
  var _lastPosition = _initialPosition;
  LatLng get initialPosition => _initialPosition;
  LatLng get lastPosition => _lastPosition;

  AppState(){
    checkGPS();
    _getUserLocation();
  }


  checkGPS() async{
    bool conn = await Geolocator().isLocationServiceEnabled();
    if(conn == false){
      locationServiceActive = false;
    } else {
      locationServiceActive = true;
    }
    notifyListeners();
  }

  void _getUserLocation() async{
    Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    print("/////////////////////////////////////////////////////////////////////////////////position");
    print(position);

    _initialPosition = LatLng(position.latitude, position.longitude);
    notifyListeners();
  }
}
flutter maps flutter-provider
1个回答
1
投票

您的问题是您需要在类构造函数中使用await checkgps()_getUserLocation(),问题是您无法从类的构造函数中运行异步函数,因此您需要执行以下操作。首先,您需要删除_getUserLocation()中的空隙或将其设为Future<void>,然后添加。

//Add to your class 
initalization() async {
    await _checkGPS();
    await getUserLocation();
  }

//This in a widget will prove it works
 @override
  void initState() {
    AppState().initalization();
    print('Location ${AppState().initialPosition}');
    super.initState();
  }
© www.soinside.com 2019 - 2024. All rights reserved.