skip to Main Content

My make a droneapp.I develop app from flutter.But ı new learned to flutter.My purpose is use firebase realtime and flutter_map and see drone location.But i am not solved to this error.Please help me
Project Code;


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(),
    );
  }
}

When I changed the values ​​in firebase, I wanted to reflect it to the location in the application.

2

Answers


  1. You can get better answers if you say which line you are getting the error, and paste the build method. The only think i know about your code is that the initState run only once when the page that contains the widget show up, if _getCurrentLocation() is not in build method your widget will never update. I would like to help more but i dont know firebase.

    Login or Signup to reply.
  2. Probably because event.snapshot.value["Lat"] can be null and the LatLng class instances are not null.
    You can fix this by adding
    _currentLocation = LatLng(event.snapshot.value?["Lat"] ?? 0, event.snapshot.value["Lng"] ?? 0);

    ?? is a null-aware operator, the expression means that, if the value of event.snapshot.value?["Lat"] in the prefs instance is null then assign an default value (which is 0) to LatLng class.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search