Sample code for 30+ languages & platforms
Dart

Page Through All Contacts

See more Google APIs Examples

Demonstrates how to page through the entire list of Google Contacts.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // This example requires the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  // --------------------------------------------------------------------------------------------------------
  // Note: The code for setting up the Chilkat REST object and making the initial connection can be done once.
  // Once connected, the REST object may be re-used for many REST API calls.
  // (It's a good idea to put the connection setup code in a separate function/subroutine.)
  // --------------------------------------------------------------------------------------------------------

  // It is assumed we previously obtained an OAuth2 access token.
  // This example loads the JSON access token file 
  // saved by this example: Get Google Contacts OAuth2 Access Token

  final jsonToken = CkJsonObject();
  try {
    jsonToken.loadFile('qa_data/tokens/googleContacts.json');
  } on ChilkatException {
    print('Failed to load googleContacts.json');
    return;
  }

  final gAuth = CkAuthGoogle();
  gAuth.accessToken = jsonToken.stringOf('access_token');

  final rest = CkRest();

  // Connect using TLS.
  final bAutoReconnect = true;
  rest.connect('www.google.com', 443, true, bAutoReconnect);

  // Provide the authentication credentials (i.e. the access token)
  rest.setAuthGoogle(gAuth);

  // ----------------------------------------------
  // OK, the REST connection setup is completed..
  // ----------------------------------------------

  var startIndex = 1;
  final maxResults = 25;
  // The totalResults will get updated with the correct value in the 1st loop iteration..
  var totalResults = 100;
  // To retrieve the contacts in pages of 25 each, we need to send the following for each page.

  // 	GET /m8/feeds/contacts/default/full?max-results=25&start-index=<startIndex>
  // 	GData-Version: 3.0

  final sbMaxResults = CkStringBuilder();
  sbMaxResults.appendInt(maxResults);
  final sbStartIndex = CkStringBuilder();

  var loopIteration = 0;
  while (startIndex <= totalResults) {

    sbStartIndex.clear();
    sbStartIndex.appendInt(startIndex);

    rest.clearAllHeaders();
    rest.clearAllQueryParams();
    rest.addHeader('GData-Version', '3.0');
    rest.addQueryParam('start-index', sbStartIndex.getAsString());
    rest.addQueryParam('max-results', sbMaxResults.getAsString());

    final sbResponseBody = CkStringBuilder();
    try {
      rest.fullRequestNoBodySb('GET', '/m8/feeds/contacts/default/full', sbResponseBody);
    } on ChilkatException catch (e) {
      print(e.lastErrorText);
      return;
    }

    // A successful response will have a status code equal to 200.
    if (rest.responseStatusCode != 200) {
      print('response status code = ${rest.responseStatusCode}');
      print('response status text = ${rest.responseStatusText}');
      print('response header: ${rest.responseHeader}');
      print('response body: ${sbResponseBody.getAsString()}');
      return;
    }

    // If the 200 response was received, then the contacts XML is contained
    // in the response body.
    final xml = CkXml();
    xml.loadSb(sbResponseBody, false);

    // Now let's parse the XML...

    // Get the the total number of results, the start index, and the items per page.
    // We'll likely NOT get the full list, but will instead get the 1st page.
    totalResults = xml.getChildIntValue('openSearch:totalResults');
    final startIndex2 = xml.getChildIntValue('openSearch:startIndex');
    final itemsPerPage = xml.getChildIntValue('openSearch:itemsPerPage');
    print('totalResults = $totalResults');
    print('startIndex = $startIndex2');
    print('itemsPerPage = $itemsPerPage');

    // Iterate over each contact.
    final numEntries = xml.numChildrenHavingTag('entry');
    var i = 0;
    while (i < numEntries) {
      xml.i = i;
      print('${loopIteration * maxResults + i + 1} ----');
      print('title: ${xml.getChildContent('entry[i]|title')}');

      final idUrl = xml.getChildContent('entry[i]|id');
      print('id: $idUrl');

      try {
        final fullName = xml.chilkatPath('entry[i]|gd:name|gd:fullName|*');
        print('fullName: $fullName');
      } on ChilkatException {
        // xml.chilkatPath() failed; continue anyway.
      }

      try {
        final emailAddress = xml.chilkatPath('entry[i]|gd:email|(address)');
        print('email address: $emailAddress');
      } on ChilkatException {
        // xml.chilkatPath() failed; continue anyway.
      }

      // Find the photo link and check to see if this contact has a photo.
      try {
        final xLink = xml.getChildWithAttr('link', 'rel', 'http://schemas.google.com/contacts/2008/rel#photo');
        // Get the photo etag.
        final bHasPhoto = xLink.hasAttribute('gd:etag');
        if (bHasPhoto) {
          print('This contact has a photo.');
        }
      } on ChilkatException {
        // xml.getChildWithAttr() failed; continue anyway.
      }

      i++;
    }

    startIndex += maxResults;
    loopIteration++;
  }
}