Dart/Flutter: Imports all contacts into .vcf file

190 Views Asked by At

I'm trying to copy contacts from an Android device and save them in .vcf format(such as 'Contacts.vcf') on the user's internal storage.

  • Using flutter_contacts: ^1.1.7+1 package, I've accessed and converted each contact to vCard.
  • Using the path_provider package, I've been able to write on the user's internal storage(creating and storing 'Contacts.vcf' file).

HERE IS MY CODE:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}


class _HomeScreenState extends State<HomeScreen> {
  List<String> vCardsList = [];

  void getAllContactsFromDeviceAndSaveTovcfFile() async {
    bool isPermissionGranted = await FlutterContacts.requestPermission();
    List<Contact> contacts = await FlutterContacts.getContacts();
    for (Contact contact in contacts) {
      vCardsList.add(contact.toVCard());
    }
    for (int i = 0; i < vCardsList.length; i++) {
    }

    PermissionStatus permissionStatus = await Permission.storage.request();
    final Directory? externalStorageDirectoryPath =
        await getExternalStorageDirectory();
    if (externalStorageDirectoryPath != null) {
      File file = File('${externalStorageDirectoryPath.path}/contacts.vcf');

      for (int i = 0; i < vCardsList.length; i++) {
        print(vCardsList.length);

        file.writeAsString(vCardsList[i], mode: FileMode.writeOnlyAppend);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    getAllContactsFromDeviceAndSaveTovcfFile();
    return const Scaffold(
      body: PlaceHolder(),
    );
  }
}

Finally, I'm trying to copy the List of vCards into this 'Contacts.vcf' file(I'm expecting that all the vCards would be copied to this 'Contacts.vcf' file and I would be able to import this file in the future to import all my contacts on my device).

Any help would be appreciated. Moreover, if you think there is a better way to achieve my final goal, that would be very helpful.

Thanks in Advance!

0

There are 0 best solutions below