【问题标题】:LateInitializationError: Field currentPosition is not initialized - FlutterLateInitializationError:字段 currentPosition 未初始化 - Flutter
【发布时间】:2021-11-27 11:59:01
【问题描述】:

我一直在尝试制作一个可以获取用户位置并将其转换为本地地址的应用程序。我不明白这里的错误以及如何解决它。 错误:LateInitializationError: Field 'currentposition' has not been initialized.

我正在尝试使用 setState 下的当前位置来显示地区、子地区、街道名称和邮政编码,但即使这样仍然会抛出错误。 我在一开始就将其定义为 String currentAddress = 'My Address'; 后期位置当前位置;

我已附上以下代码。
我正在使用 Geolocator 作为定位服务和地理编码来将该信息转换为地址。

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



class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  String currentAddress = 'My Address';
  late Position currentposition ;
  Future<Position?> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      Fluttertoast.showToast(msg: 'Please enable Your Location Service');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        Fluttertoast.showToast(msg: 'Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      Fluttertoast.showToast(
          msg:
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    try {
      List<Placemark> placemarks =
      await placemarkFromCoordinates(position.latitude, position.longitude);

      Placemark place = placemarks[0];

      setState(() {
        currentposition = position;
        currentAddress =
        "${place.locality}, ${place.subLocality},${place.street}, ${place.postalCode}";
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Location'),
      ),
      body: Center(
          child: Column(
            children: [
              Text(currentAddress),
              currentposition != null
                  ? Text('Latitude = ' + currentposition.latitude.toString())
                  : Container(),
              currentposition != null
                  ? Text('Longitude = ' + currentposition.longitude.toString())
                  : Container(),
              TextButton(
                  onPressed: () {
                    _determinePosition();
                  },
                  child: Text('Locate me'))
            ],
          ),),
    );
  }
}

【问题讨论】:

  • 请改用Position? currentposition;。无论如何,您都在进行空值检查。没有理由不能为空。

标签: flutter location


【解决方案1】:

您正在处理设置在Future&lt;Position?&gt; _determinePosition() 下的futurecurrentposition。因此,该值是在初始化之前读取的。使用FutureBuilder 处理这种情况。

 body:FutureBuilder(
            future: _determinePosition(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return CircularProgressIndicator();
              } else if (snapshot.hasError) {
                return Text("Error ");
              }else if(snapshot.hasData){
              .... return your widget

更多关于FutureBuilder

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 2021-12-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 2021-10-27
    • 2021-12-29
    • 2022-01-16
    相关资源
    最近更新 更多