Im using FlutterFlow and im implementing a function where it should fetch on the user's device and save all his contacts to show them on a list view.
The code Im using is this one
// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!
import 'package:contacts_service/contacts_service.dart';
Future buscarContactos(String? userId) async {
// Add your function code here!
List<Contact> contacts = await ContactsService.getContacts();
final instance = FirebaseFireStore.instance;
CollectionReference collection =
instance.collection('users').doc(userId).collection('contacts');
late Map<String, dynamic> data;
if (contacts != null)
data = {
'contacts': contacts
.map((k) => {
if (k.displayName != null) 'name': k.displayName,
if (k.emails!.isNotEmpty && k.emails != null)
'email': k.emails?.first.value,
if (k.phones!.isNotEmpty && k.phones != null)
'phone': k.phones?.first.value
.toString()
.replaceAll(new RegExp(r"\s\b|\b\s"), "")
.replaceAll(new RegExp(r'[^\w\s]+'), '')
.replaceAll(new RegExp(r'/^(?!\s*$).+/'), "")
})
.toList(),
};
collection
.doc(userId)
.set(data)
.then((value) => print("Contacts Updated"))
.catchError((error) => print("Failed to update Contacts: $error"));
return userId;
}
I ask the user about the necessary permissions,importing the necessary packages on the code above and implementing neccesary dependencies.