rekabhq / background_locator

A Flutter plugin for updating location in background.
MIT License
287 stars 321 forks source link

Null check operator used on a null value when using a static function #322

Open jesussmile opened 2 years ago

jesussmile commented 2 years ago

I have a static void method that always returns a null check error , The same line of code works fine with other methods/ functions. I have no clue why this is happening.

The configMaps.dart (global declaration)

User? currentFirebaseUser;

Next on main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);
  await Firebase.initializeApp();
  currentFirebaseUser = FirebaseAuth.instance.currentUser;
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
      alert: true, badge: true, sound: true);
  runApp(MyApp());
}

HomeTabPages

class _HomeTabPageState extends State < HomeTabPage >
    with AutomaticKeepAliveClientMixin, OSMMixinObserver {

        isDriverAvailable = false; //check if user is online or offline, initially offline

        //under the widget tree

        RaisedButton(
            color: dsc.driverStatusClr,
            onPressed: () {
                if (isDriverAvailable != true) {
                    isDriverAvailable = true;
                    makeDriverOnlineNow();
                    getLocationLiveUpdates();
                    displayToastMessage( //displays correct currentFirebaseUserId
                        currentFirebaseUser!.uid.toString(), context);
                    Provider.of < AppData > (context, listen: false)
                        .buttonOnline(Colors.green, "Online");

                    // });
                    displayToastMessage("You are Online now", context);
                } else {
                    Provider.of < AppData > (context, listen: false)
                        .buttonOnline(Colors.black, "Offline");
                    driverOffline();

                    displayToastMessage("You are Offline now", context);
                    isDriverAvailable = false;
                }
            },
            child: Padding(
                padding: EdgeInsets.all(17),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                        Text(
                            dsc.driverStatusTxt,
                            style: TextStyle(
                                fontSize: 20.0,
                                fontWeight: FontWeight.bold,
                                color: Colors.white),
                        ),
                        Icon(
                            Icons.phone_android,
                            color: Colors.white,
                            size: 26,
                        )
                    ],
                ),
            ),
        )),

    void makeDriverOnlineNow() async {
        geo.Position position = await geo.Geolocator.getCurrentPosition(
            desiredAccuracy: geo.LocationAccuracy.high);

        await Geofire.initialize("availableDrivers");

        //there is no null check error here
        await Geofire.setLocation(
            currentFirebaseUser!.uid, position.latitude, position.longitude);

        await rideRequestRef!.set("searching");
        rideRequestRef!.onValue.listen((event) {});
    }

void getLocationLiveUpdates() async {
    print(currentFirebaseUser.toString()); //I get the correct value till here but when it goes to call back its null
    return await BackgroundLocator.registerLocationUpdate(
        backgroundLocationCallBack,
        autoStop: false,
        // disposeCallback: backgroundLocationDisposeCallBack,

        androidSettings: AndroidSettings(
            accuracy: LocationAccuracy.NAVIGATION,
            interval: 5,
            distanceFilter: 0,
            client: LocationClient.google,
            androidNotificationSettings: AndroidNotificationSettings(
                notificationChannelName: 'Location tracking',
                notificationTitle: 'Start Location Tracking',
                notificationMsg: 'Track location in background',
                notificationBigMsg:
                'Background location is on to keep the app up-tp-date with your location. This is required for main features to work properly when the app is not running.',
                notificationIconColor: Colors.grey,
            )));
}

static void backgroundLocationCallBack(LocationDto location) async {

    print("from background location +${location.latitude}");

    //if (isDriverAvailable)

    //I get a null check used on a null value error here on currentFirebaseUser!.uid
    await Geofire.setLocation(
        currentFirebaseUser!.uid, location.latitude, location.longitude);
    print("from geofire +${location.latitude}");
    print(currentFirebaseUser.toString());
}

The two methods here makeDriverOnlineNow() and getLocationLiveUpdates() both implement

 await Geofire.setLocation(
        currentFirebaseUser!.uid, position.latitude, position.longitude);

For makeDriverOnlineNow() there is no error but for getLocationLiveUpdates() there is a null check error used on a null value at currentFirebaseUser!.uid