简体   繁体   English

当我尝试多次调用该服务时,Flutter 中的 Easy Geofencing 出现问题

[英]Issues with Easy Geofencing in Flutter when i am trying to call the service more then one time

i am trying to check if the user in specific geofencing zone using the Easy geofencing package but every time i call the EasyGeofencing.startGeofenceService() and EasyGeofencing.getGeofenceStream() with new position ( pointedLatitude, pointedLongitude, radiusMeter) the service do not work and the console print "Parse value===> false" if any one know how i solve this problem please help me, i am stuck since a week.我正在尝试使用 Easy geofencing package 检查用户是否处于特定的地理围栏区域,但每次我使用新的 position(pointedLatitude、pointedLongitude、radiusMeter)调用 EasyGeofencing.startGeofenceService() 和 EasyGeofenceStream() 时,服务都不起作用,并且控制台打印“Parse value ===> false”如果有人知道我如何解决这个问题请帮助我,我被困了一个星期。

this is my code这是我的代码

import 'dart:async';
import 'package:easy_geofencing/easy_geofencing.dart';

import 'package:geolocator/geolocator.dart';
import 'package:easy_geofencing/enums/geofence_status.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/domain/models/shop_model.dart';
import 'package:flutter_application_1/presentation/resources/assets_manager.dart';
import 'package:flutter_application_1/presentation/resources/color_manager.dart';
import 'package:flutter_application_1/presentation/resources/values_manager.dart';
import 'package:flutter_application_1/presentation/sidebars/cardWidget.dart';
import 'package:flutter_application_1/presentation/sidebars/profileSideBar.dart';
import 'package:flutter_application_1/services/shop_services.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';

class ShopsDownBar extends StatefulWidget with ChangeNotifier {
  ShopsDownBar({Key? key}) : super(key: key);

  @override
  State<ShopsDownBar> createState() => _ShopsDownBarState();
}

class _ShopsDownBarState extends State<ShopsDownBar>
    with SingleTickerProviderStateMixin<ShopsDownBar> {
  StreamSubscription<GeofenceStatus>? geofenceStatusStream;
  StreamSubscription<EasyGeofencing>? easyGeofencingStream;
  Geolocator geolocator = Geolocator();
  String geofenceStatus = '';
  bool isReady = false;
  int raduis = 25;
  double? longitude;
  double? latitude;
  Position? position;
  late StreamController<bool> isOpenStreamController;
  late Stream<bool> isOpenNStream;
  late StreamSink<bool> isOpenNSink;
  late AnimationController _animationControler;
  List<Shops> shops = [];

  getCurrentPosition() async {
    position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    print("LOCATION => ${position?.toJson()}");
    isReady = (position != null) ? true : false;
  }

  setLocation() async {
    await getCurrentPosition();
    print("POSITION => ${position!.toJson()}");
  }

  final _animationDuration = const Duration(milliseconds: 500);
  setShops() {
    ShopServices().fetchShops().then((value) {
      setState(() {
        if (value != null) {
          for (int i = 0; i < value.length; i++) {
            shops.add(Shops(
              type: value[i].type,
              shopStatus: value[i].shopStatus,
              rewards: value[i].rewards,
              id: value[i].id,
              shopName: value[i].shopName,
              shopAddress: value[i].shopAddress,
              markerShop: value[i].markerShop,
              createdAt: value[i].createdAt,
              updatedAt: value[i].updatedAt,
            ));
          }
        }
      });
    });
  }

  void onIconPressed() {
    final animationStatus = _animationControler.status;
    final isAnimationDone = animationStatus == AnimationStatus.completed;
    if (isAnimationDone) {
      isOpenNSink.add(false);
      _animationControler.reverse();
    } else if (Provider.of<ProfileSideBar>(context, listen: false).isOpen ==
        false) {
      isOpenNSink.add(true);
      _animationControler.forward();
    }
  }

  @override
  void initState() {
    setShops();
    getCurrentPosition();
    if (isReady) {
      print('jawna behi');
      setState(() {
        setLocation();
      });
    }

    _animationControler =
        AnimationController(vsync: this, duration: _animationDuration);
    isOpenStreamController = PublishSubject<bool>();

    isOpenNStream = isOpenStreamController.stream;
    isOpenNSink = isOpenStreamController.sink;
    super.initState();
  }

  @override
  void dispose() {
    _animationControler.dispose();
    isOpenStreamController.close();
    isOpenNSink.close();
    EasyGeofencing.stopGeofenceService();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    var height = size.height;
    var width = size.width;

    return StreamBuilder<bool>(
        initialData: false,
        stream: isOpenNStream,
        builder: (context, isOpenAsync) {
          return AnimatedPositioned(
            duration: _animationDuration,
            top: isOpenAsync.data == false ? height * 0.91 : height * 0.24,
            bottom: AppSize.s1_5,
            right: AppSize.s1_5,
            left: AppSize.s1_5,
            child: Column(
              children: [
                Align(
                  child: GestureDetector(
                    onTap: () {
                      onIconPressed();
                    },
                    child: Container(
                      //  alignment: Alignment.cen,
                      padding: const EdgeInsets.only(
                        left: AppMargin.m60,
                        right: AppMargin.m60,
                        top: AppMargin.m8,
                      ),
                      child: Icon(
                        isOpenAsync.data == true
                            ? Icons.close
                            : Icons.wallet_giftcard,
                        size: AppSize.s28,
                        color: ColorManager.primary,
                      ),
                      decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(AppSize.s40),
                            topRight: Radius.circular(AppSize.s40)),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                      margin: const EdgeInsets.only(
                          left: AppMargin.m16, right: AppMargin.m16),
                      height: height / 1.4,
                      width: width,
                      decoration: BoxDecoration(
                        color: ColorManager.white,
                        borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(AppSize.s28),
                            topRight: Radius.circular(AppSize.s28)),
                      ),
                      child: shops.isNotEmpty
                          ? ListView.builder(
                              itemBuilder: (context, index) {
                                return Padding(
                                  padding: const EdgeInsets.only(
                                      bottom: AppPadding.p8,
                                      top: AppPadding.p18),
                                  child: Giftcart(
                                    ontap: () {
                                      // print("starting geoFencing Service");
                                      EasyGeofencing.startGeofenceService(
                                          pointedLatitude: shops[index]
                                              .markerShop
                                              .locations
                                              .latitude
                                              .toString(),
                                          pointedLongitude: shops[index]
                                              .markerShop
                                              .locations
                                              .longitude
                                              .toString(),
                                          radiusMeter: raduis.toString(),
                                          eventPeriodInSeconds: 5);

                                      geofenceStatusStream ??=
                                          EasyGeofencing.getGeofenceStream()!
                                              .listen((GeofenceStatus? status) {
                                        print(status.toString());
                                        setState(() {
                                          geofenceStatus = status.toString();
                                        });
                                        if (status.toString() ==
                                            'GeofenceStatus.enter') {
                                          print("entered");
                                         
                                        } else {
                                          print("not entered");
                                        }
                                      });
                                    },
                                    shopName: shops[index].shopName,
                                    details: shops[index].shopAddress,
                                    imagePath: ImageAssets.logo1,
                                  ),
                                );
                              },
                              itemCount: shops.length)
                          : Padding(
                              padding: const EdgeInsets.fromLTRB(
                                  AppPadding.p100,
                                  AppPadding.p100,
                                  AppPadding.p100,
                                  AppPadding.p200),
                              child: CircularProgressIndicator(
                                valueColor: AlwaysStoppedAnimation<Color>(
                                    ColorManager.primary),
                              ),
                            )),
                ),
              ],
            ),
          );
        });
  }
}

giftCart widget礼品车小部件

import 'package:flutter/material.dart';
import 'package:flutter_application_1/presentation/resources/color_manager.dart';
import 'package:flutter_application_1/presentation/resources/values_manager.dart';
//import 'package:flutter_application_1/presentation/resources/font_manager.dart';

class Giftcart extends StatelessWidget {
  final String shopName;
  final String details;
  final String imagePath;

  final void Function() ontap;

  const Giftcart({
    Key? key,
    required this.ontap,
    required this.shopName,
    required this.details,
    required this.imagePath,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    var height = size.height;
    var width = size.width;
    return Center(
      child: Container(
        decoration: BoxDecoration(
          color: ColorManager.white,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: ColorManager.grey,
              offset: const Offset(0, 0),
              blurRadius: 10,
            ),
          ],
        ),
        height: height * 0.1,
        width: width * 0.8,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
                height: height * 0.15,
                width: width * 0.15,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(40),
                ),
                child: Image.asset(imagePath)),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  height: height * 0.02,
                ),
                Text(
                  shopName,
                  style: Theme.of(context).textTheme.subtitle2,
                  textAlign: TextAlign.end,
                ),
                SizedBox(
                  height: height * 0.01,
                ),
                Text(
                  details,
                  style: Theme.of(context).textTheme.bodyText1,
                  textAlign: TextAlign.start,
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(right: 10.0),
              child: SizedBox(
                height: height * 0.12,
                width: width * 0.12,
                child: FloatingActionButton(
                    backgroundColor: ColorManager.primary,
                    onPressed: ontap,
                    child: Icon(
                      Icons.card_giftcard,
                      size: AppSize.s18,
                      color: ColorManager.white,
                    )),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

the Screen the button on the left is for checking the geofenceStatus屏幕左侧的按钮用于检查地理围栏状态

在此处输入图像描述

this is the package doc这是 package 文档

Add "geofenceStatusStream = null;"添加“geofenceStatusStream = null;” after stopGeofenceService as below:停止地理围栏服务后如下:

setState(() {
              EasyGeofencing.stopGeofenceService();
              geofenceStatusStream!.cancel();
              geofenceStatusStream = null;
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在尝试使用 flutter chopper 和内置值调用方法时会出错? - Why am I getting an error when trying to call a method with flutter chopper and built value? 我正在尝试使用 https.MultipartRequest 在 Flutter 中调用 API - I am trying to make a call to an API with https.MultipartRequest in Flutter 当我使用 equatable 时如何多次发出空状态 - How to emit empty state more than one time when I am using equatable 当我在 flutter 的 didChangeDependencies 中调用多个提供商时,它显示错误 - when I call more than one provider in didChangeDependencies in flutter ,it shows me error 当我试图运行项目时,它会产生错误 - In flutter when I am trying to run project it is giving error Flutter:尝试启动时收到过时的消息 - Flutter: I am getting an outdated message when trying to launch 当我在颤振中反复调用时,如何一次性启动功能? - How to launch function one time when I have a recurrent call in flutter? 我正在尝试使用负载更多 package - I am trying to use load more package 我正在尝试使用 Flutter 中的路由将 map 数据从一个页面发送到其他页面。并收到此错误 - I am trying to send map data from one page to other using routes in Flutter . and getting this Error 我正在尝试在 flutter 中使用地图功能 - i am trying to use map function in flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM