How to get contact number from contact_service Flutter - 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

Related

how to wait for a value and add it to list flutter

I have this piece of code
Future<List<RoomModel>> getTeacherRooms(String email) async {
var docs = await _roomRepo.getTeacherRooms(email);
List<RoomModel> rooms = [];
docs.map((doc) async {
var room = await toRoom(doc);
rooms.add(room);
}).toList();
return rooms;
}
I need to wait for toRoom() to return a value then put it in rooms
the problem is with this code is that rooms is returned empty
I just used "pskink" answer to solve this problem
this is the code
Future<List<RoomModel>> getTeacherRooms(String email) async {
var docs = await _roomRepo.getTeacherRooms(email);
return await Future.wait(docs.map((doc) => toRoom(doc)).toList());
}

How to change index of an item in list in Flutter

I am working on a messaging app and I need help on a feature. Chat Users are stores inside a list and it is shown in a List View. When new message come to each chatuser(item in the list) I need it change that item as first. So recent contacts will be shown first like other social medias. I need to know how to change index of it to first. For swapping I need to take two items which in this case I cant do. So when new message comes to an item that item should be the first in that list. What should I do
have a look at this:
class Contact {
final List<String> messages;
final String name;
Contact({required this.name, this.messages = const []});
}
void main() {
List<Contact> contacts = [Contact(name: "userA"), Contact(name: "userB"), Contact(name: "userC")];
void receiveMessage(String username, String message) {
final Contact user = contacts.where((e) => e.name == username).first;
contacts.remove(user);
user.messages.add(message);
contacts.insert(0, user);
}
receiveMessage("userB", "hello");
receiveMessage("userC", "helloooo");
receiveMessage("userB", "hello000000000");
for (var contact in contacts) {
print(contact.name);
for (var message in contact.messages) {
print(message);
}
print("------------------------");
}
}

Dart List doesnt get updated with forEach loop

I am using this package to retrieve device's contacts. The lib retrieve 427 contacts and I want to loop the whole list so that I can create another list and send it to the back-end. The problem is looping does not work this the function return before looping is completed.
Here the function I use:
Future<QueryResult> uploadContacts() async {
final List<Contact> rawContacts =
(await ContactsService.getContacts(withThumbnails: false)).toList();
List<ContactInput> contactsListInput;
print('contactsListInput length: ${rawContacts.length}');
rawContacts.forEach((contact) {
print('contact: $contact'); //PRINTED JUST ONCE
//Contact can have more than 1 number. We need them all
contact.phones.forEach((phone) {
final contactInput =
ContactInput(name: contact.displayName, phone: phone.value);
contactsListInput.add(contactInput);
});
});
print('contactsListInput length: ${contactsListInput.length}'); //NEVER PRINT ANYTHING
final ContactsListInput input =
ContactsListInput(contacts: contactsListInput);
final MutationOptions _options = MutationOptions(
document: SyncContactsMutation().document,
variables: SyncContactsArguments(input: input).toJson());
return client.mutate(_options);
}
I have also tried using for loop and the same thing happened.
for (int i = 0; i < rawContacts.length; i++) {
final contact = rawContacts[i];
final contactInput =
ContactInput(name: contact.displayName, phone: contact.phones.first.value);
contactsListInput.add(contactInput);
}
print('contactsListInput length: ${contactsListInput.length}'); //NEVER CALLED
And I also tried Future.forEach
await Future.forEach(rawContacts, (contact) async {
print('contact: $contact');
//Since contact can have more than one number we loop them too.
await Future.forEach(contact.phones, (phone) async {
final contactInput =
ContactInput(name: contact.displayName, phone: phone.value);
contactsListInput.add(contactInput);
});
});
How to fix this? Any help will be much appreciated.
I have fixed it as
Future<QueryResult> uploadContacts() async {
final Iterable<Contact> rawContacts =
(await ContactsService.getContacts(withThumbnails: false));
final Iterable<ContactInput> contacts = rawContacts.expand((contact) => contact.phones.map(
(phone) =>
ContactInput(name: contact.displayName, phone: phone.value)));
final input = ContactsListInput(contacts: contacts);
final MutationOptions _options = MutationOptions(
document: SyncContactsMutation().document,
variables: SyncContactsArguments(input: input).toJson());
return client.mutate(_options);
}
Credit goes to #pskink and #loganrussell48
You should use it as a dynamic type object. Try something like this:
(event.snapshot.value as dynamic).forEach()
Try and see if it works.

Flutter can''t send sms using fluttersms

I'm trying to send sms after my app scanned a qrcode that contains a phone number.
I'm using FlutterSMS package for this but it seems doesn't work as supposed to do, it is not sending the sms. any help?
void _sendSMS(String message, List<String> recipents) async {
String _result =
await FlutterSms.sendSMS(message: message, recipients: recipents)
.catchError((onError) {
print(onError);
});
print(_result);
}
Future _scan() async {
String barcode = await scanner.scan();
List data = barcode.split("|");
String id = data[0];
String phoneNumber = data[1];
String message = "Halo! Pakaian anda sudah selesai di proses, silahkan ambil di gerai kami -LaundryKu";
setState(() {
this.id = id;
this.barcode = barcode;
this.phoneNumber = phoneNumber;
});
_sendSMS(message, data[1]);
}
Brother there is little mistake
second argument is List
_sendSMS(message, recipents);
So you need to Add you Contact Number to List
List<String> recipents = new List();
recipents.add(data[1].toString());
/// then the Msg in Variable
String message = "This is a test message!";
Final pass both variable as parameters in function
_sendSMS(message, recipents);
Finally you are Done ;)

How to upload contacts as Iterable from Flutter to Firestore

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.