Skip to content

Updated cloud firestore. #41

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 54 additions & 48 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,19 @@ class MyApp extends StatefulWidget {
}

class _MyAppState extends State<MyApp> {
GoogleMapController _mapController;
TextEditingController _latitudeController, _longitudeController;
GoogleMapController? _mapController;
late TextEditingController _latitudeController, _longitudeController;

// firestore init
// Firestore initialization
final _firestore = FirebaseFirestore.instance;
GeoFlutterFire geo;
Stream<List<DocumentSnapshot>> stream;
late GeoFlutterFire geo;
late Stream<List<DocumentSnapshot<Map<String, dynamic>>>> stream;
final radius = BehaviorSubject<double>.seeded(1.0);
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

double _value = 20.0;
String _label = '';

@override
void initState() {
super.initState();
Expand All @@ -42,21 +45,25 @@ class _MyAppState extends State<MyApp> {
geo = GeoFlutterFire();
GeoFirePoint center = geo.point(latitude: 12.960632, longitude: 77.641603);
stream = radius.switchMap((rad) {
var collectionReference = _firestore.collection('locations');
// .where('name', isEqualTo: 'darshan');
return geo.collection(collectionRef: collectionReference).within(
center: center, radius: rad, field: 'position', strictMode: true);

/*
****Example to specify nested object****

var collectionReference = _firestore.collection('nestedLocations');
// .where('name', isEqualTo: 'darshan');
return geo.collection(collectionRef: collectionReference).within(
center: center, radius: rad, field: 'address.location.position');

*/
var collectionReference = _firestore
.collection('locations')
.withConverter<Map<String, dynamic>>(
fromFirestore: (snapshot, _) => snapshot.data()!,
toFirestore: (value, _) => value,
);
return geo
.collection(collectionRef: collectionReference)
.within(
center: center,
radius: rad,
field: 'position',
strictMode: true,
)
.map((docs) => docs
.map((doc) => doc as DocumentSnapshot<Map<String, dynamic>>)
.toList());
});

}

@override
Expand All @@ -76,20 +83,15 @@ class _MyAppState extends State<MyApp> {
title: const Text('GeoFlutterFire'),
actions: <Widget>[
IconButton(
onPressed: _mapController == null
? null
: () {
_showHome();
},
onPressed: _mapController == null ? null : _showHome,
icon: Icon(Icons.home),
)
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) {
return StreamTestWidget();
}));
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => StreamTestWidget()));
},
child: Icon(Icons.navigate_next),
),
Expand Down Expand Up @@ -124,7 +126,7 @@ class _MyAppState extends State<MyApp> {
value: _value,
label: _label,
activeColor: Colors.blue,
inactiveColor: Colors.blue.withOpacity(0.2),
inactiveColor: Colors.blue.withValues(alpha: 0.2),
onChanged: (double value) => changed(value),
),
),
Expand Down Expand Up @@ -173,7 +175,7 @@ class _MyAppState extends State<MyApp> {
MaterialButton(
color: Colors.amber,
child: const Text(
'Add nested ',
'Add nested',
style: TextStyle(color: Colors.white),
),
onPressed: () {
Expand All @@ -192,16 +194,15 @@ class _MyAppState extends State<MyApp> {
void _onMapCreated(GoogleMapController controller) {
setState(() {
_mapController = controller;
// _showHome();
//start listening after map is created
stream.listen((List<DocumentSnapshot> documentList) {
// Start listening after map is created
stream.listen((List<DocumentSnapshot<Map<String, dynamic>>> documentList) {
_updateMarkers(documentList);
});
});
}

void _showHome() {
_mapController.animateCamera(CameraUpdate.newCameraPosition(
_mapController?.animateCamera(CameraUpdate.newCameraPosition(
const CameraPosition(
target: LatLng(12.960632, 77.641603),
zoom: 15.0,
Expand All @@ -211,14 +212,15 @@ class _MyAppState extends State<MyApp> {

void _addPoint(double lat, double lng) {
GeoFirePoint geoFirePoint = geo.point(latitude: lat, longitude: lng);
_firestore
.collection('locations')
.add({'name': 'random name', 'position': geoFirePoint.data}).then((_) {
_firestore.collection('locations').add({
'name': 'random name',
'position': geoFirePoint.data,
}).then((_) {
print('added ${geoFirePoint.hash} successfully');
});
}

//example to add geoFirePoint inside nested object
// Example to add GeoFirePoint inside a nested object
void _addNestedPoint(double lat, double lng) {
GeoFirePoint geoFirePoint = geo.point(latitude: lat, longitude: lng);
_firestore.collection('nestedLocations').add({
Expand All @@ -244,21 +246,25 @@ class _MyAppState extends State<MyApp> {
});
}

void _updateMarkers(List<DocumentSnapshot> documentList) {
documentList.forEach((DocumentSnapshot document) {
Map<String, dynamic> snapData = document.data();
final GeoPoint point = snapData['position']['geopoint'];
_addMarker(point.latitude, point.longitude);
});
void _updateMarkers(List<DocumentSnapshot<Map<String, dynamic>>> documentList) {
for (var document in documentList) {
final data = document.data();
if (data != null) {
final positionData = data['position'] as Map<String, dynamic>?;
if (positionData != null) {
final geoPoint = positionData['geopoint'] as GeoPoint?;
if (geoPoint != null) {
_addMarker(geoPoint.latitude, geoPoint.longitude);
}
}
}
}
}

double _value = 20.0;
String _label = '';

changed(value) {
void changed(double value) {
setState(() {
_value = value;
_label = '${_value.toInt().toString()} kms';
_label = '${_value.toInt()} kms';
markers.clear();
});
radius.add(value);
Expand Down
115 changes: 69 additions & 46 deletions example/lib/streambuilder_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,63 +9,89 @@ class StreamTestWidget extends StatefulWidget {
}

class _StreamTestWidgetState extends State<StreamTestWidget> {
Stream<List<DocumentSnapshot>> stream;
final _firestore = FirebaseFirestore.instance;
final geo = GeoFlutterFire();
late Stream<List<DocumentSnapshot<Map<String, dynamic>>>> stream;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final GeoFlutterFire geo = GeoFlutterFire();

// ignore: close_sinks
var radius = BehaviorSubject<double>.seeded(1.0);
final BehaviorSubject<double> radius = BehaviorSubject<double>.seeded(1.0);

double _value = 20.0;
String _label = '';

@override
void initState() {
super.initState();
final center = geo.point(latitude: 12.960632, longitude: 77.641603);
stream = radius.switchMap((rad) {
var collectionReference = _firestore.collection('locations');
stream = radius.switchMap((double rad) {
var collectionReference = _firestore.collection('locations').withConverter<Map<String, dynamic>>(
fromFirestore: (snapshot, _) => snapshot.data() ?? {},
toFirestore: (value, _) => value,
);
// GeoFlutterFire returns a stream of List<DocumentSnapshot<Object?>>.
// Map each document to the correct type.
return geo.collection(collectionRef: collectionReference).within(
center: center, radius: rad, field: 'position', strictMode: true);
center: center,
radius: rad,
field: 'position',
strictMode: true,
).map((docs) => docs.map((doc) => doc as DocumentSnapshot<Map<String, dynamic>>).toList());
});
}

@override
void dispose() {
_latitudeController.dispose();
_longitudeController.dispose();
radius.close();
super.dispose();
}

final TextEditingController _latitudeController = TextEditingController();
final TextEditingController _longitudeController = TextEditingController();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: <Widget>[
StreamBuilder(
stream: stream,
builder: (BuildContext context,
AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
if (snapshots.connectionState == ConnectionState.active &&
snapshots.hasData) {
print('data ${snapshots.data}');
return Container(
height: MediaQuery.of(context).size.height * 2 / 3,
child: ListView.builder(
itemBuilder: (context, index) {
final doc = snapshots.data[index];
Map<String, dynamic> data = doc.data();
print(
'doc with id ${doc.id} distance ${data['distance']}');
GeoPoint point = data['position']['geopoint'];
return ListTile(
title: Text(
doc.id,
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text('${point.latitude}, ${point.longitude}'),
trailing: Text(
'${data['documentType'] == DocumentChangeType.added ? 'Added' : 'Modified'}'),
);
},
itemCount: snapshots.data.length,
),
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
Expanded(
child: StreamBuilder<List<DocumentSnapshot<Map<String, dynamic>>>>(
stream: stream,
builder: (BuildContext context,
AsyncSnapshot<List<DocumentSnapshot<Map<String, dynamic>>>> snapshots) {
if (snapshots.connectionState == ConnectionState.active && snapshots.hasData) {
print('data ${snapshots.data}');
return Container(
height: MediaQuery.of(context).size.height * 2 / 3,
child: ListView.builder(
itemCount: snapshots.data!.length,
itemBuilder: (context, index) {
final doc = snapshots.data![index];
// Force non-null since we expect documents to contain data.
final Map<String, dynamic> data = doc.data()!;
print('doc with id ${doc.id} distance ${data['distance']}');
// Assume that data['position'] is a Map with a 'geopoint' key.
final GeoPoint point = (data['position'] as Map<String, dynamic>)['geopoint'] as GeoPoint;
return ListTile(
title: Text(
doc.id,
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text('${point.latitude}, ${point.longitude}'),
trailing: Text(
data['documentType'] == DocumentChangeType.added ? 'Added' : 'Modified',
),
);
},
),
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
),
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
Expand All @@ -76,7 +102,7 @@ class _StreamTestWidgetState extends State<StreamTestWidget> {
value: _value,
label: _label,
activeColor: Colors.blue,
inactiveColor: Colors.blue.withOpacity(0.2),
inactiveColor: Colors.blue.withValues(alpha: 0.2),
onChanged: (double value) => changed(value),
),
),
Expand All @@ -85,14 +111,11 @@ class _StreamTestWidgetState extends State<StreamTestWidget> {
);
}

double _value = 20.0;
String _label = '';

changed(value) {
void changed(double value) {
setState(() {
_value = value;
print(_value);
_label = '${_value.toInt().toString()} kms';
_label = '${_value.toInt()} kms';
});
radius.add(value);
}
Expand Down
4 changes: 2 additions & 2 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ description: Demonstrates how to use the Geoflutterfire2 plugin.
publish_to: "none"

environment:
sdk: ">=2.1.0 <3.0.0"
sdk: ^3.6.1

dependencies:
flutter:
Expand All @@ -20,7 +20,7 @@ dev_dependencies:
geoflutterfire2:
path: ../

cloud_firestore: ^4.4.4
cloud_firestore: ^5.6.5
google_maps_flutter: ^2.2.5

# For information on the generic Dart part of this file, see the
Expand Down
Loading