簡體   English   中英

無法無條件調用方法“[]”,因為接收者可以為“null”。 錯誤

[英]The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Error

我制作了一個無人機應用程序。我從 flutter 開發應用程序。但我新學到了 flutter。我的目的是使用 firebase 實時和 flutter_map 並查看無人機位置。但我沒有解決這個錯誤。請幫助我項目代碼;


import 'package:google_fonts/google_fonts.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:droneapps/crud.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:droneapps/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart' /* as latLng*/;

class MapWidgetW extends StatefulWidget {
  @override
  _MyMapState createState() => _MyMapState();
}

class _MyMapState extends State<MapWidgetW> {
  late LatLng _currentLocation;

  @override
  void initState() {
    super.initState();
    _getCurrentLocation();
  }

  void _getCurrentLocation() {
    final databaseReference = FirebaseDatabase.instance.ref("Location");
    databaseReference.child("Location").onValue.listen((DatabaseEvent event) {
      setState(() {
        _currentLocation =
            LatLng(event.snapshot.value["Lat"], event.snapshot.value["Lng"]);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return FlutterMap(
      options: MapOptions(),
    );
  }
}

當我更改 firebase 中的值時,我想將其反映到應用程序中的位置。

如果您說出您在哪一行收到錯誤並粘貼構建方法,您可以獲得更好的答案。 關於你的代碼,我唯一知道的是當包含小部件的頁面出現時,initState 只運行一次,如果 _getCurrentLocation() 不在構建方法中,你的小部件將永遠不會更新。 我想提供更多幫助,但我不知道 firebase。

可能是因為event.snapshot.value["Lat"]可以是 null 而LatLng class 實例不是 null。您可以通過添加_currentLocation = LatLng(event.snapshot.value?["Lat"]?? 0, event.snapshot.value["Lng"]?? 0);來解決這個問題_currentLocation = LatLng(event.snapshot.value?["Lat"]?? 0, event.snapshot.value["Lng"]?? 0);

?? 是空感知運算符,表達式意味着,如果event.snapshot.value?["Lat"]在 prefs 實例中的值為 null,則將默認值(即 0)分配給 LatLng class。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM