How to upload contacts as Iterable from Flutter to Firestore - flutter

I'm creating an app which will upload all contacts to Firestore database with map type. But below code do not upload contacts to Firestore. Please help.
I have been trying to fetch contacts from my phone to Firestore using Flutter app. I used contact_services library to fetch contacts. Even after trying some similar examples, I could not my contacts to Firestore using map type. Where do I make changes so that I can upload all my contacts as map value to Firestore
final Iterable<Contact> contacts = await ContactsService.getContacts(withThumbnails: false);
Firestore.instance
.collection('contacts')
.document(firebaseUser.uid)
.setData({
'contact':{ contacts.map((Contact contact){ 'name': contacts.displayName,contacts.phone})}
});
I expected to display all my contacts in firestore with map type, but actual output is none were uploaded.

I am sure you have fixed this since this is an old post. But there are a few things incorrect with how you are using the map method id Dart.
You named your element variable "contact" and not "contacts" so that is the variable you should be referencing "contact" to get your information. So it would be contact.displayName.
You are not returning anything. Because there is no "=>" there is no implicit return and because there is no "return" there is no explicit return.
Also, what you are returning from the map method is an Iterable to the contact field.
I am not sure what you are trying to accomplish here. Are you trying to insert a nested object? If so, your phone is also missing a key

Little late but, this is for the reference for the Firestore version ^0.16.0.
// your list of contacts in _contacts.
List<Contact> _contacts = [];
final FirebaseFirestore _db = FirebaseFirestore.instance;
CollectionReference _ref = _db.collection(collectionName);
Future<void> syncContacts({uid}) async {
try {
Map<String, dynamic> _data;
if (_contacts != null)
_data = {
'contacts': _contacts
.map((k) => {
'name ': k.displayName,
'phone': k.phones.first.value
.toString()
.replaceAll(new RegExp(r"\s\b|\b\s"), "")
.replaceAll(new RegExp(r'[^\w\s]+'), '')
})
.toList(),
};
log(_data.toString());
await _service.reference().doc(uid).set(_data, SetOptions(merge: true));
} catch (e) {
log(e.toString());
} finally {
notifyListeners();
}
}
P.S I have used flutter_contact library to get contacts from the device.

Related

Why can't my Firebase Cloud Firestore Collection update (.update) when I have already created one (.set)?

'I have a Firebase Cloud Firestore Collection. When I am trying to update it, it can't find it. I can however see the newly created file in my collection. Anyone who knows how to fix this? I am fairly new in coding. Thank you in advance.
This the part of the code where we get the error, it is also mentioned elsewhere:'
class DatabaseService {
final String? uid;
DatabaseService({this.uid});
//collection reference
final CollectionReference listenCollection =
FirebaseFirestore.instance.collection('listen');
Future updateUserData(String status, String name, int score) async {
return await listenCollection.doc(uid).set({
'status': status,
'name': name,
'score': score,
});
}
Future updateName(String name) async {
return await listenCollection.doc(uid).update({'name': name});
}
Stream<QuerySnapshot> get listen {
return listenCollection.snapshots();
}
}

Getting all documents uids from firestore and add them to a list .flutter

I created a new collection named users on my firestore project. Im trying to get a list of all auto generated id's in that collection. So far I tried
late List<String> userID = [];
Future getID() async {
await FirebaseFirestore.instance.collection('users').get().then(
(snapshot) => snapshot.docs.forEach((document) {
userID.add(document.reference.id);
}),
);
}
But whenever I try to access the Strings of id's in the list , it returns an empty list
getID is a future method. It will take some to fetch data. After getting data you need to call setState to update the UI. You dont need to await and .then same time
try
Future getID() async {
FirebaseFirestore.instance.collection('users').get().then((snapshot) {
snapshot.docs.forEach((document) {
userID.add(document.reference.id);
});
setState(() {});
});
}
It would be great to use FutureBuilder for future method.

Create a list inside an item of another list

I have a list of teams to which the logged in user belongs to in my application. Within each team there is a list with the Uids of each team member (teamMembersUid). There is also an empty list in which the information of each user (teamMembers) must be inserted.
Objective: I want to take the Uids of each user in teamMembersUid, extract their information from the database (Firebase firestore) and introduce it into teamMembers list. Here is the team model with the lists:
class TeamModel {
String? uid;
String? teamName;
List<String>? teamMembersUid;
List<UserModel>? teamMembers;
List<String>? publicationsUid;
List<String>? notifications;
List<String>? instancesUid;
TeamModel(
{this.uid,
this.teamName,
this.teamMembersUid,
this.teamMembers,
this.instancesUid,
this.notifications,
this.publicationsUid});
//receiving data from server
factory TeamModel.fromMap(map) {
return TeamModel(
uid: map['uid'],
teamName: map['teamName'],
teamMembersUid: map['teamMembersUid'] is Iterable
? List.from(map['teamMembersUid'])
: null,
teamMembers:
map['teamMembers'] is Iterable ? List.from(map['teamMembers']) : null,
publicationsUid: map['publicationsUid'] is Iterable
? List.from(map['publicationsUid'])
: null,
notifications: map['notifications'] is Iterable
? List.from(map['notifications'])
: null,
instancesUid: map['instancesUid'] is Iterable
? List.from(map['instancesUid'])
: null,
//List.from(['teamMembersUid']), //castFrom adapts teamMembersUid to be a List
);
}
The following function (getTeamsInfoWithUsers) is responsible for:
Create a list with the teams to which the user belongs from firestore.
Extract the Uids of each member of each team.
Get the information from each user from firestore.
Create a list with the information of each user of each team and enter it in teamMembers.
UserModel userData;
List<TeamModel> retVal = [];
try {
//Create a list with the teams to which the user belongs from firestore
final data = await _firestore
.collection("teams")
.where("teamMembersUid", arrayContains: userUid)
.get();
List<TeamModel> data_m =
List.from(data.docs.map((doc) => TeamModel.fromMap(doc)));
//Extract the Uids of each member of each team.
retVal = data_m
.map((team) {
team.teamMembersUid!.map((userUid) async {
//Get the information from each user from firestore.
userData = await getUserInfo(userUid);
//Create a list with the information of each user of each team and enter it in teamMembers.
team.teamMembers!.add(userData);
});
})
.cast<TeamModel>()
.toList();
} catch (e) {
print(e);
}
return retVal;
}```
Problem: The current user belongs to 4 teams and each team has 3 users. Debugging I put a breakpoint in team.teamMembers!.add(userData); line. Since there are 4 teams and each team has 3 users you should see the code stop on that line 12 times, 3 for each team. Instead, it only stops 3 times and doesn't seem to create the list of teamMembers in the data_m variable either. I don't understand why it doesn't work.
Error:
Null error
how about this
retVal = data_m
.map((team) {
team.teamMembersUid!.map((userUid) async {
userData = await getUserInfo(userUid);
team.teamMembers!.add(userData);
}).toList();
})
.cast<TeamModel>()
.toList();
VS

How to fetch data from Firestore and display them in Flutter?

I'm a beginner in Flutter and firestore. I have a collection in firestore with following order:
event->'a user specific id'->post->'a post id->'post details'. you can see hereFirestore1 and hereFirestore2
When I try to fetch the 'postdetails', only thing I get is 'Instance of 'DocumentSnapshot',see hereResponse
What i tried:
getEvents() async {
setState(() {
_isLoading = true;
});
DocumentSnapshot snapshot = await eventref
.doc(uid)
.collection('post')
//.orderBy('Date', descending: true)
.doc()
.get();
print('Snapshot : ${snapshot}');
return snapshot;
// setState(() {
// _isLoading = false;
// print(event);
// });
}
I have also made a model for events. See hereEvent Model
I want to fetch data and display them as card.
Any help?
Thanks in Advance
print('Snapshot : ${snapshot.data()["Date"]}');
Using data() you can access the fields value.
snapshot.get("field_name")
You need to ask flutter to retrieve the fields inside the document snapshot.
Will need a more detailed order of your firestore collection and document to provide the exact code. You may follow the sample below:
On firestore:
-Collection: "users"
---Document: "userId"
-------Field: "username"
-------Field: "birthdate"
Code:
DocumentSnapshot doc =await _firestore.collection("users").doc(userId).get();
print(doc.get('username'));
print(doc.get('birthdate'));

How to get contact number from contact_service Flutter

I'm useing contact_service to manage my contacts. I have fetch all contacts as a list. And I want to access fields with phone number of each contact. I want to get it as a string but the atribute in Contact class is
Iterable<Item> phones
Do You know how can I get a phone number from this ?
Link to this package :
https://pub.dev/packages/contacts_service
Thanks in advance
For every Iterable<Item> phones, Item.value returns the phone number string.
List<String> names = [];
List<String> phones = [];
Iterable<Contact> _contacts = await ContactsService.getContacts(withThumbnails: false);
_contacts.forEach((contact) {
contact.phones.toSet().forEach((phone) {
names.add(contact.displayName ?? contact.givenName);
phones.add(phone.value);
});
});
List<Contact> _contacts;
Future<void> refreshContacts() async {
// Load without thumbnails initially.
var contacts = (await ContactsService.getContacts(
withThumbnails: false, iOSLocalizedLabels: iOSLocalizedLabels))
.toList();
setState(() {
_contacts = contacts;
});
}
and use this contact list to render widget inside ListView/Column
Follow complete example here
https://github.com/lukasgit/flutter_contacts/blob/master/example/lib/contacts_list_page.dart