如何在后台将用户的当前位置从Flutter应用程序发送到Firebase数据库?

bqujaahr  于 2023-05-29  发布在  Flutter
关注(0)|答案(1)|浏览(263)

我使用flutter_background_service,geolocator和cloud_firestore包来获取用户位置,即使应用程序处于后台或前台,并将lat,long发送到firebase数据库。但它只在我不初始化firebase时才起作用,一个通知显示当前的lat,long,但一旦我初始化firebase,它就不会将当前的lat,long推送到数据库并抛出此错误([ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception:[core/no-app]未创建Firebase应用程序“[DEFAULT]”-调用Firebase.initializeApp
但我已经初始化了
我想发送当前用户的纬度和经度数据库,即使应用程序是在后台或前葫芦。这是我的代码

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

  await initializ();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(MaterialApp(
    home: First(),
  ));
}


Future initializ() async {
  final service = FlutterBackgroundService();
  await service.configure(
      iosConfiguration: IosConfiguration(),
      androidConfiguration:
          AndroidConfiguration(isForegroundMode: true, onStart: OnStart));
  await service.startService();
}

@pragma('vm:entry-point')
void OnStart(ServiceInstance service) async {
  if (service is AndroidServiceInstance) {
    service.on('setAsForeground').listen((event) {
      service.setAsForegroundService();
    });

    service.on('setAsBackground').listen((event) {
      service.setAsBackgroundService();
    });
  }

  service.on('stopService').listen((event) {
    service.stopSelf();
  });

  Timer.periodic(const Duration(seconds: 2), (timer) async {
    if (service is AndroidServiceInstance) {
      if (await service.isForegroundService()) {
        Position position = await Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.high);
        String long = position.longitude.toString();
        String lat = position.latitude.toString();
        print(lat);
        var db = FirebaseFirestore.instance;
        var users = db.collection("rashi");
        await users.add({"lat": long.toString(), "lng": lat.toString()});
        service.setForegroundNotificationInfo(
            title: "Asif", content: "longitude : $long , latitude : $lat ");
      }
    }
  });
}
5lhxktic

5lhxktic1#

这样调用方法
void main()async { WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(选项:DefaultFirebaseOptions.currentPlatform); int getchar();
runApp(MaterialApp(home:public void run();}
首先初始化firebaseapp,然后调用其他方法

相关问题