cache

mail@pastecode.io avatar
unknown
dart
2 months ago
2.0 kB
3
Indexable
Never
class ServicesProvider extends ChangeNotifier {
  final box = GetStorage();
  List<Services_Item> items = [];
  bool _isLoaded = false;
  int _categoryLength = 0;

  bool get isLoaded => _isLoaded;
  int get categoryLength => _categoryLength;

  void fetchData() async {
    final counts = await FirebaseFirestore.instance
        .collectionGroup('services')
        .orderBy('postedDate', descending: true)
        .count()
        .get();

    int cached = configures.preferences!.getInt('servicesCount') ?? 0;

    if (!_isLoaded && cached != counts.count) {
      try {
        print('start fetching data');
        final snapshot = await FirebaseFirestore.instance
            .collectionGroup('services')
            .orderBy('postedDate', descending: true)
            .get(const GetOptions(source: Source.serverAndCache));

        items =
            snapshot.docs.map((e) => Services_Item.fromJson(e.data())).toList();

        print(items);

        box.write('servicesItems', items);
        configures.preferences?.setInt('servicesCount', snapshot.docs.length);

        _isLoaded = true;

        _categoryLength = snapshot.docs
            .where((element) => element['category'] == 'کڕین و فرۆشتن')
            .length;
        notifyListeners();
      } catch (error) {
        print('Error fetching data: $error');
      }
    } else {
      try {
        print('start fetching cached data');
        var cachedDocumentsJson = box.read('servicesItems');

        if (cachedDocumentsJson != null && items.isEmpty) {
          items = (cachedDocumentsJson as List<dynamic>)
              .map((itemJson) => Services_Item.fromJson(itemJson))
              .toList();
          // print(items);
        } else { 
          print('Cached data had loaded');
          // print(items);
        }
        notifyListeners();
      } catch (e) {
        print('Error fetching cached data: $e');
      }
    }
  }
}
Leave a Comment