fetch method

Fetch the active messages; on success, auto-show a session-start message.

Implementation

Future<List<NexusInAppMessage>> fetch() async {
  await _loadCounts();
  try {
    final res = await _http.post('/partner/inapp/active', {
      if (_id.distinctId != null) 'distinctId': _id.distinctId,
      'deviceKey': _id.deviceKey,
      'properties': _wireProperties(),
      'context': _context(),
    });
    final list = (res?['messages'] as List?) ?? const [];
    final all = list.whereType<Map>().map((m) => NexusInAppMessage.fromJson(m.cast<String, dynamic>())).toList();
    final tests = all.where((m) => m.isTest).toList();
    _active = all.where((m) => !m.isTest).toList();
    NexusLog.debug('inapp: ${_active.length} active${tests.isEmpty ? '' : ', ${tests.length} test'}');
    _listenForTests(res?['testDevice'] == true);
    if (tests.isNotEmpty) {
      // A test from the console: show it now, whatever is on screen.
      NexusLog.info('inapp: showing test "${tests.first.id}"');
      current.value = tests.first;
    } else if (_cfg.inAppAutoShow) {
      _showNext(null);
    }
  } catch (e) {
    NexusLog.warn('inapp fetch failed: $e');
  }
  return _active;
}