fetchRecords method

Future<List<AirtableRecord>> fetchRecords(
  1. String tableName, {
  2. bool paginate = true,
  3. String view = 'Grid view',
})

Fetches records from the specified tableName.

  • paginate: If true (default), fetches all pages of records.
  • view: The view in Airtable from which to fetch records (default is 'Grid view').

Returns a Future that resolves to a list of AirtableRecord.

Throws an AirtableException if the request fails.

Implementation

Future<List<AirtableRecord>> fetchRecords(String tableName,
    {bool paginate = true, String view = 'Grid view'}) async {
  List<AirtableRecord> allRecords = [];
  String? offset;

  do {
    var uri = Uri.parse('$_endpoint/$baseId/$tableName').replace(
      queryParameters: {
        if (offset != null) 'offset': offset,
        'view': view, // Add view parameter
      },
    );

    final response = await http.get(
      uri,
      headers: {
        'Authorization': 'Bearer $apiKey',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode == 200) {
      final jsonData = jsonDecode(response.body);
      allRecords.addAll((jsonData['records'] as List)
          .map((recordJson) => AirtableRecord.fromJson(recordJson))
          .toList());
      offset = jsonData['offset'];
    } else {
      // Get detailed error information from the response body
      final errorBody = jsonDecode(response.body);
      throw AirtableException(
        message: 'Failed to fetch records',
        details: errorBody['error']?['message'],
      );
    }

    if (!paginate) {
      break;
    }
  } while (offset != null);

  return allRecords;
}