getStructuredTexts method

Future<List<Text>?> getStructuredTexts(
  1. String projectId, {
  2. required String apiKey,
  3. required String baseUrl,
  4. bool acceptCache = true,
})

Returns the list of the Text objects contained on Ditto

Throws FailedFetchException if the request fails

Implementation

Future<List<Text>?> getStructuredTexts(
  String projectId, {
  required String apiKey,
  required String baseUrl,
  bool acceptCache = true,
}) async {
  if (acceptCache) {
    final data = await DittoCacheManager.instance().getFile(_textsKey);
    if (data != null) {
      log('Fetched ditto resources from cache', name: 'flutter_ditto');
      getStructuredTexts(
        projectId,
        apiKey: apiKey,
        baseUrl: baseUrl,
        acceptCache: false,
      );
      return (data['data'] as List).map((m) => Text.fromJson(m)).toList();
    }
  }

  final response = await _provider.get(
    baseUrl: baseUrl,
    apiKey: apiKey,
    path: '/projects/$projectId',
    queryParams: {'format': 'structured'},
  );
  if (response.statusCode == 200) {
    log('Downloaded updated ditto resources', name: 'flutter_ditto');
    final json = (jsonDecode(response.body) as Map<String, dynamic>);
    final newData = json.entries
        .map(
          (e) => Text.fromJson((e.value as Map<String, dynamic>)
            ..putIfAbsent('key', () => e.key)),
        )
        .toList();

    DittoCacheManager.instance().store(_textsKey, {'data': newData});

    return newData;
  }
  throw FailedFetchException(response.body);
}