属性“纬度”不能无条件访问,因为接收者可能为“null”。尝试将访问设置为有条件的(使用“?.”)

发布于 2025-01-09 09:34:34 字数 3145 浏览 1 评论 0原文

我在文本中面临空安全问题( "纬度:" + currentPosition.latitude.toString(), )这一行。我不知道如何使 currentPosition.latitude 不为 null 帮助我解决这些问题。

它给了我这个属性“latitude”不能无条件访问,因为接收器可以为“null”。 尝试使访问成为有条件的(使用“?.”)或向目标添加空检查(“!”)。错误。

无法无条件访问属性“longitude”,因为接收者可以为“null”。 尝试使访问成为有条件的(使用“?.”)或向目标添加空检查(“!”)。错误

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeApp(),
    );
  }
}

class HomeApp extends StatefulWidget {
  HomeApp({Key? key}) : super(key: key);

  @override
  State<HomeApp> createState() => _HomeAppState();
}

class _HomeAppState extends State<HomeApp> {
  String currentAddress = 'my address';
  Position? currentPosition;
  Future<Position?> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      Fluttertoast.showToast(msg: 'Please keep your location on.');
    }
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        Fluttertoast.showToast(msg: 'Location permission is denied.');
      }
    }
    if (permission == LocationPermission.deniedForever) {
      Fluttertoast.showToast(msg: 'Location permission is denies forever.');
    }
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    try {
      List<Placemark> placemark =
          await placemarkFromCoordinates(position.latitude, position.longitude);
      Placemark place = placemark[0];
      setState(() {
        currentPosition = position;
        currentAddress =
            "${place.locality},${place.postalCode},${place.country}";
      });
    } catch (e) {
      print(e);
    }
  }

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

I am facing a null safety issue in Text(
"Latitude: " + currentPosition.latitude.toString(),
) this line. i dont know how to make currentPosition.latitude not null help me with this guys.

It gives me this The property 'latitude' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!'). error.

The property 'longitude' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!'). error

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeApp(),
    );
  }
}

class HomeApp extends StatefulWidget {
  HomeApp({Key? key}) : super(key: key);

  @override
  State<HomeApp> createState() => _HomeAppState();
}

class _HomeAppState extends State<HomeApp> {
  String currentAddress = 'my address';
  Position? currentPosition;
  Future<Position?> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      Fluttertoast.showToast(msg: 'Please keep your location on.');
    }
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        Fluttertoast.showToast(msg: 'Location permission is denied.');
      }
    }
    if (permission == LocationPermission.deniedForever) {
      Fluttertoast.showToast(msg: 'Location permission is denies forever.');
    }
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    try {
      List<Placemark> placemark =
          await placemarkFromCoordinates(position.latitude, position.longitude);
      Placemark place = placemark[0];
      setState(() {
        currentPosition = position;
        currentAddress =
            "${place.locality},${place.postalCode},${place.country}";
      });
    } catch (e) {
      print(e);
    }
  }

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘虞初梦 2025-01-16 09:34:34

更改为:

 currentPosition!.latitude.toString()

由于您检查了 currentPosition 不为空,因此您可以使用 ! 来表示“我知道它可以为空,但我也知道此时它绝对不是” t”。

Change to this:

 currentPosition!.latitude.toString()

Since you check that currentPosition is not null, you can use the ! as a way of saying "I know it can be null, but I also know that at this point it definitely isn't".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文