GithubHelp home page GithubHelp logo

fluttercommunity / firestore_helpers Goto Github PK

View Code? Open in Web Editor NEW
48.0 48.0 19.0 420 KB

Firestore Helpers - Firestore helper function to create dynamic and location based queries. Maintainer: @escamoteur

Home Page: https://pub.dev/packages/firestore_helpers

License: MIT License

Dart 86.95% Batchfile 0.44% Java 4.21% Objective-C 2.41% Shell 1.78% Ruby 4.20%

firestore_helpers's People

Contributors

escamoteur avatar guplersaxanoid avatar ihorklimov avatar jeroen-meijer avatar netwiser avatar sgeschke-alphaport avatar slightfoot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firestore_helpers's Issues

Is this library first loading all data before filtering?

Hi ,
I have theoretic question is this library before filtering loading all data then filter?
or filter the server side then it make all queries more productive and cheaper because if i have 10k users and i want to find the closet one by geopoint i dont want that all my data will return(cost a lot of money)

Best regards sahar :)

The library works with GeoHash ?

Hi
I'm searching a solution to do a Query of Stores nearly by User position, i tested a library GeoFlutterFire, but i can't add more conditions for example, type's store, name's store, etc. the library don't works, and i found your response in StackOverFlow Your Response

I'm reading the information about firestore_helpers, it says _"DISCLAIMER: As some users pointed out, FireStore does not correctly compare GeoPoints at this time which lead to more data might be returned from the server than the server-side query intended. "
My Question is, if the library can help me ?

Actual Number of Document Reads

Hi,

We are currently building an app using Flutter and one of our key functionality is getting nearby Restaurant records within the area of the mobile user's location from Firestore. Our main problem is that if we have thousands of restaurant documents, then it will be an expensive operation given that Firestore charges by the number of documents retrieved. We need to only query the nearby records and not query all the records only to perform the computation of distance one by one.

If we implement your location based query sample, are we only going to be charged with the number of results(only the queried nearby restaurants) that it returns? For example, we have 10,000 restaurants/documents in our collection but only 100 restaurants/documents are actually nearby, are we going to be charged for only 100 reads? Our main concern is that maybe this library also queries all the documents in a collection and then also performs the calculation per document.

Thanks

Can't apply clientSitefilters

Trying to query nearby drivers. Everything works pretty good until I'm trying to filter results with clientSiteFilters.

The code I'm using:

  Stream<List<dynamic>> nearbyDriversStream(area) {
    return getDataInArea(
      area: Area(area, 0.7),
      source: Firestore.instance.collection('drivers'),
      locationFieldNameInDB: 'position',
      mapper: (document) => document.data,
      locationAccessor: (item) => item['position'],
      distanceMapper: (item, dist) {
        item['distance'] = dist;
        return item;
      },
      clientSitefilters: [(item) => item['distance'] != 0.0], // Try to filter out current driver location
    );
  }

  _handleButtonPress() {
    nearbyDriversSubscription =
        nearbyDriversStream(currentLocation).listen((data) {
      print(data);
      nearbyDriversSubscription.cancel();
    });
  }

In this case I'm having an exception that says:

I/flutter (10905): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (10905): The following assertion was thrown while handling a gesture:
I/flutter (10905): type '() => List<(dynamic) => bool>' is not a subtype of type 'List<(dynamic) => bool>'

Compiler also complains if I'm trying to pass just (item) => item['distance'] != 0.0

What is the right way to use clientSiteFilters?

radiusInKilometers 120.0km returns 400.0 km location

I'm trying to fetch document inside circle of 120.0 km.
But it returns 400.0 km away.
Is this a bug or I'm making some mistake?

This is Osaka Abeno.

   var lat = 34.643839; 
   var lng = 135.512383;
   var area = GeoPoint(lat, lng);

This is Tokyo Station.

   var lat = 35.681167; 
   var lng = 139.767052;
   var area = GeoPoint(lat, lng);

I searched these distance in google map and it returns over 400 km.
I fetched like so.

Stream<List<Items>> itemsStream() {
    return getDataInArea(
    area: Area(area, 120.0), 
    source: Firestore.instance.collection('items'), 
      locationFieldNameInDB: 'location', 
      mapper: (document) {
        print(document.data);
      },
    );
  }

V4.0.0 null safety

Hi,

I just published V4.0.0. As I don't have any active FireStore projects I couldn't really test it.
Please give it a try and tell me if you encounter any problems

Cheers
Thomas

/example is broken.

Aside from the example breaking down when trying to receive the package:
[example] flutter packages get Running "flutter packages get" in example... Because firestorehelpertest depends on firestore_helpers from path which doesn't exist (could not find package firestore_helpers at "..\"), version solving failed.

(managed to get through by deleting the path area)

I receive 2 errors regarding the databaseservice.dart file:
screenshot 2018-12-17 at 15 50 05

I found this package exactly what I needed but it needs to be mended before use.

Omitted properties in QueryConstraints

Why does the QueryConstraint class in firestore_helpers.dart not include the properties arrayContainsAny, whereIn, whereNotIn that are defined in the Query class of cloud_firestore package?

Is there any conflict happening in the program by adding them? If yes, what are they? If not, would a pull request to add those properties be welcomed?

Multiple Constrains

I'm trying to use multiple constrains but it's not working. please help.

help print

Coordenadas Variable
[-35.20710125507246, -55.76097692727273, -34.36652154492754, -54.70643147272727]


Stream<List<Desejo>> getEvents(eventCollection,
    {List<QueryConstraint> constraints}) {
  try {
    Query ref = buildQuery(
        collection: eventCollection,
        constraints: constraints,
        orderBy: [
          new OrderConstraint("dataPretendida", true),
          new OrderConstraint('lat', true),
          new OrderConstraint('lng', true)
        ]);
    var r =
        ref.snapshots().map((snapShot) => snapShot.documents.map((eventDoc) {
              Desejo event = Desejo.fromJson(eventDoc.data);
              event.key = eventDoc.documentID;
              return event;
            }).toList());
    r.toList().then((v) {
      print(v.toString());
    });
    return r;
  } on Exception catch (ex) {
    print(ex);
  }
  return null;
}
 getEvents(Firestore.instance.collection('desejos'), constraints: [
    new QueryConstraint(
        field: 'dataPretendida',
        isGreaterThanOrEqualTo: DateTime.now().microsecondsSinceEpoch),
    new QueryConstraint(
        field: 'lat',
        isGreaterThanOrEqualTo: coordenadas[2],
        isLessThanOrEqualTo: coordenadas[0]),
    new QueryConstraint(
        field: 'lng',
        isGreaterThanOrEqualTo: coordenadas[3],
        isLessThanOrEqualTo: coordenadas[1]),
    /*new QueryConstraint(field: 'lng', isGreaterThanOrEqualTo: coordenadas[1]),
    new QueryConstraint(field: 'lng', isLessThanOrEqualTo: coordenadas[3]),*/
  ]);

Error message.
All where filters other than whereEqualTo() must be on the same field. But you have filters on 'dataPretendida' and 'lat' at com.google.firebase.firestore.Query.zza(SourceFile:91) at com.google.firebase.firestore.Query.zza(SourceFile:281) at com.google.firebase.firestore.Query.whereLessThanOrEqualTo(SourceFile:166) at io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin.getQuery(CloudFirestorePlugin.java:151) at io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin.onMethodCall(CloudFirestorePlugin.java:455) at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:191) at io.flutter.view.FlutterNativeView.handlePlatformMessage(FlutterNativeView.java:152) at android.os.MessageQueue.nativePollOnce(Native Method) at android.os.MessageQueue.next(MessageQueue.java:326) at android.os.Looper.loop(Looper.java:160) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 09-25 01:10:26.276 4820-6135/com.rbsoftware.bartner E/flutter: [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception: PlatformException(error, All where filters other than whereEqualTo() must be on the same field. But you have filters on 'dataPretendida' and 'lat', null) #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:547:7) #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:279:18) <asynchronous suspension> #2 Query.snapshots.<anonymous closure> (file:///C:/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.8.0/lib/src/query.dart:57:37) #3 _runGuarded (dart:async/stream_controller.dart:804:24) #4 _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:217:7) #5 _ControllerStream._createSubscription (dart:async/stream_controller.dart:817:19) #6 _StreamImpl.listen (dart:async/stream_impl.dart:466:9) #7 new _ForwardingStreamSubscription (dart:async/stream_pipe.dart:123:10) #8 _ForwardingStream._createSubscription (dart:async/stream_pipe.dart:91:16) #9 _ForwardingStream.listen (dart:async/stream_pipe.dart:86:12) #10 Stream.toList (dart:async/stream.dart:959:10) #11 getEvents (package:bartner/elementos/Menu/MeusDesejosPage.dart:84:7) #12 PrepDesejosScreen (package:bartner/elementos/Menu/MeusDesejosPage.dart:96:3) #13 _MenuPrincipal.getDocumentNearBy.<anonymous closure>.<anonymous closure> (package:bartner/elementos/Menu/MenuPrincipal.dart:177:24) #14 State.setState (package:flutter/src/widgets/framework.dart:1125:30) #15 _MenuPrincipal.getDocumentNearBy.<anonymous closure> (package:bartner/elementos/Menu/MenuPrincipal.dart:176:7) #16 _RootZone.runUnary (dart:async/zone.dart:1381:54) #17 _FutureListener.handleValue (dart:async/future_impl.dart:129:18) #18 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45) #19 Future._propagateToListeners (dart:async/future_impl.dart:662:32) #20 Future._complete (dart:async/future_impl.dart:467:7) #21 _SyncCompleter.complete (dart:async/future_impl.dart:51:12) #22 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart) <asynchronous suspension> #23 Location.getLocation (package:location/location.dart:12:8) #24 _MenuPrincipal.getDocumentNearBy (package:bartner/elementos/Menu/MenuPrincipal.dart:156:14) #25 _MenuPrincipal.initState (package:bartner/elementos/Menu/MenuPrincipal.dart:188:5) #26 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3751:58) #27 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3617:5) #28 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2907:14) #29 Element.updateChild (package:flutter/src/widgets/framework.dart:2710:12) #30 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4654:14) #31 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2907:14) #32 Element.updateChild (package:flutter/src/widgets/framework.dart:2710:12) #33 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3653:16) #34 Element.rebuild (package:flutter/src/widgets/framework.dart:3495:5) #35 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3622:5) #36 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3617:5) #37 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2907:14) #38 Element.updateChild (package:flutter/src/widgets/framework.dart:2710:12) #39 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4654:14) #40 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2907:14) #41 Element.updateChild (package:flutter/src/widgets/framework.dart:2710:12) #42 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4654:14) #43 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2907:14)

GetDataInArea with OrderBy

Hello, firstly thanks a lot for this plugin, it's very useful and it works perfectly!. Secondly, i need help. I want to use getDataInArea method with orderBy from Firebase. I need to get items from Firebase collection orderBy timestamp in area. I have the following code:

Stream<List<Items>> itemsStream() {
    var sydney = GeoPoint(-33.865143, 151.209900); // Sydney, e.g.
    return getDataInArea(
      area: Area(sydney, 2.0), // I want to search in 2 km, e.g.
      source: firestore.collection('items'), // I need `orderBy` this `items` collection by `timestamp` or whatever property. I try `firestore.collection('items').orderBy('timestamp')` but didn't work *.
      locationFieldNameInDB: 'location', // Required to search in area =)
      mapper: (document) {
        return _buildItemFrom(document); // Map the result.
      },
    );
  }
  • Error: PlatformException(error, Invalid query. You have an inequality where filter (whereLessThan(), whereGreaterThan(), etc.) on field 'location' and so you must also have 'location' as your first orderBy() field, but your first orderBy() is currently on field 'timestamp' instead., null).

Is there any way to orderBy collection when i search in area?

Thank you!

error showing in after addin in depandacy

error showing when i add following dependencies

cupertino_icons: ^0.1.2
cloud_firestore: ^0.9.0
firebase_auth: ^0.8.0+1
flutter_swiper:
intl:
firebase_database:
datetime_picker_formfield:
paytm:
http:
flutter_staggered_grid_view:
firestore_helpers: ^3.0.0

Issue with getDataFromQuery

I am using getDataFromQuery as shown in example, applying query constraints and getting results back as expected.
But when in FB console I manually update any item, then I get all items instead of only those which I got after applying constraints in first place.

Thanks

Limiting query shows furthest document instead of closest

I didn't want to make a new issue since the prev issue wasn't really an issue, just me not fully understanding how the function worked.

Below is the function where I can retrieve the values. When using the same latlong value and the radius is high then the values show properly, ie closest to furthest within the radius that is set, but when I set a limit to show only 1 then it shows only the furthest within that radius.

Stream<List<Mosque>> observeGeoMosques({double lat, double lon, double radius, int limitTo, Function onEmpty, Function onFailure(String e)}) {
return getDataInArea(
  area: Area(GeoPoint(lat, lon), radius), 
  source: this.mosquesCollection.limit(limitTo),
  locationFieldNameInDB: 'address.geopoint', 
  mapper: (doc) {
    return Mosque().transform(key: doc.documentID, map: doc.data);
  },
  locationAccessor: (mosque) => mosque.address.geopoint,
  distanceMapper: (mosque, distance) {
    mosque.address.distance = distance;
    return mosque;
  },
  sortDecending: true
);
}

I have a code like given below how can I use this I want display list by distance from user

[List _offers = [];

List get offers => _offers;

BuildContext buildContext;

class OffersGrid extends StatelessWidget {
OffersGrid({@required BuildContext context}) {
buildContext = context;
}

@OverRide
Widget build(BuildContext context) {
CollectionReference offerReference = Firestore.instance.collection(OFFER_COLLECTION);
Query filterQuery;

if (startPrice != 0) {
  if (filterQuery == null) {
    filterQuery = offerReference.where(OFFER_PRICE, isGreaterThanOrEqualTo: startPrice);
  } else {
    filterQuery = filterQuery.where(OFFER_PRICE, isGreaterThanOrEqualTo: startPrice);
  }
}
if (endPrice != 0) {
  if (filterQuery == null) {
    filterQuery = offerReference.where(OFFER_PRICE, isLessThanOrEqualTo: endPrice);

  } else {
    filterQuery = filterQuery.where(OFFER_PRICE, isLessThanOrEqualTo: endPrice);

  }
}

if (selectedOfferCategory != null) {
  if (filterQuery == null)
    filterQuery = offerReference.where(OFFEER_CATEGORY, isEqualTo: selectedOfferCategory.text);
  else
    filterQuery = filterQuery.where(OFFEER_CATEGORY, isEqualTo: selectedOfferCategory.text);



}




return new StreamBuilder<QuerySnapshot>(
  stream: filterQuery != null ? filterQuery.snapshots() : offerReference.snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) return new Center(child: new CircularProgressIndicator());
    if (snapshot.data.documents.length == 0) return new Center(child: new Text('No data available', style: new TextStyle(fontSize: 20.0,fontFamily: "SnackerComic",color: Colors.black),),);
    return new StaggeredGridView.count(
      physics: new BouncingScrollPhysics(),
      crossAxisCount: MediaQuery.of(context).orientation == Orientation.portrait ? 2 : 3,
      children: buildGrid(snapshot.data.documents),
      staggeredTiles: generateRandomTiles(snapshot.data.documents.length),
    );
  },
);

}
}

List buildGrid(List documents) {
List _gridItems = [];
_offers.clear();

for (DocumentSnapshot document in documents) {
_offers.add(Offer.fromDocument(document));
}

for (Offer offer in _offers) {
_gridItems.add(buildGridItem(offer));
}

return _gridItems;
}
](url)

getDataInArea returns nothing

Hi, first of all thank you so much such a helpful plugin this really saves me from a lot of works.
I tried to fetch by using getDataInArea but it returns nothing. I tried to search for what was wrong but I still can't find it. So, could you tell me what am I missing?

I set data to Firestore like so.

var lat = 34.702485;
var lng = 135.495951;
Firestore.instance.collection('helper').document('abc').setData({'location': new GeoPoint(lat, lng), 'name': 'Osaka Station'});

And fetching like so.

  Stream<List<Item>> itemsStream() {
    return getDataInArea(
      source: Firestore.instance.collection('helper'), 
      area: Area(place, 20.0), 
      locationFieldNameInDB: 'location',
      mapper: (document) {
        print(document.exists);
        print(document.data);
      },
      // serverSideOrdering: [new OrderConstraint('timeStamp', false)],
    );
  }

This returns nothing and I set breakpoint, this function ends at area it won't go further.
Can you tell what's going on?
Thank you so much again for great plugin.

sincerely,

How do i get other data from the document after filter?

I tried the example code and it worked.
But how do i get other data from the query ?

Stream<List> getLocations({GeoPoint center, double radiusInKm}) {
return getDataInArea(
source: Firestore.instance.collection('items'),
area: Area(center, radiusInKm),
locationFieldNameInDB: 'position',
mapper: (doc) => LocationSerializer().fromMap(doc.data),
locationAccessor: (item) => item.position,
// The distancemapper is applied after the mapper
distanceMapper: (item, dist) {
item.distance = dist;
return item;
});
}

What do i have to do?

Geoquery: the distance is not correct, the query find item out of area!

Hi , i use this code for location query. The result is not correct because it find location out of range and the distances are wrong. i check with google maps the distance between the point of Area and the points of firestore.

`static Stream<List> getEvents() {

Area area = new Area(new GeoPoint(42.324322, 13.7075033), 0.7);
try {
  return getDataInArea(
      area: area,
      collection: reference,
      locationFieldNameInDB: 'position',
      mapper: (eventDoc) {
        var event = Event.fromMap(eventDoc.data);
        return new EventData(event);
      },
      locationAccessor: (eventData) => eventData.event.location,
      distanceMapper: (eventData, distance) {
        eventData.distance = distance;
        return eventData;
      },
      distanceAccessor: (eventData) => eventData.distance, // filer only future events
  );
} on Exception catch (ex) {
  print(ex);
}
return null;

}
}`
How can i fix? it s a bug?

thank you

Please help -- it is not working

I can not seem to get it to work... please help me

class Test extends State<TestGeoHelpers> {
  double _lat = 51.0769547;
  double _lng = -113.9421552;

  String _geo = '';

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Test'),
      ),
      body: new Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(16.0),
        child: new Column(
          children: <Widget>[
            new RaisedButton(
              child: new Text('GEO'),
              onPressed: () {
                Area area =
                    new Area(new GeoPoint(51.0769547, -113.9421552), 0.7);
                getEvents(area);
              },
            ),
            new Text(_geo),
          ],
        ),
      ),
    );
  }

  Stream<List<EventData>> getEvents(area) {
    GeoPoint areagp = new GeoPoint(_lat, _lng);
    Area searchArea = new Area(areagp, 4.0);

    //try {
    return getDataInArea(
      source: Firestore.instance.collection('jobs'),
      area: searchArea,
      locationFieldNameInDB: 'geopoint',
      mapper: (eventDoc) {
        print(eventDoc.data['title'].toString());
      },
    );
  }
}

class Event {
  String title;
  GeoPoint geopoint;
}

class EventData {
  Event event;
  double distance;

  EventData(this.event, [this.distance]);
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.