getWidgets method

Future<List<WidgetEntry>> getWidgets({
  1. String? userId,
})

Fetch all widgets, optionally filtered by user.

On network failure, returns the last cached response for this userId when a cache has been configured. Throws if there is no cache fallback.

Implementation

Future<List<WidgetEntry>> getWidgets({String? userId}) async {
  final cacheKey = 'getWidgets_${userId ?? 'all'}';
  try {
    final uri = Uri.parse('$baseUrl/api/widgets').replace(
      queryParameters: userId != null ? {'user_id': userId} : null,
    );
    final response = await _client.get(uri, headers: _getHeaders);
    _checkResponse(response);
    await cache?.save(cacheKey, response.body);
    return WidgetResponse.fromJson(
            json.decode(response.body) as Map<String, dynamic>)
        .widgets;
  } catch (_) {
    final cached = await cache?.load(cacheKey);
    if (cached != null) return cached;
    rethrow;
  }
}