flutter 无法在dataprovider和appwrite中筛选数据

2wnc66cl  于 2023-06-24  发布在  Flutter
关注(0)|答案(1)|浏览(132)

我在Flutter应用程序中使用Provider包过滤数据时遇到了问题。我有一个项目列表,我想根据选定的类别进行筛选。然而,过滤似乎并不像预期的那样工作。
下面是相关的代码片段:

import 'dart:convert';

import 'package:appwrite/appwrite.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DataProvider with ChangeNotifier {
  final Databases database;
  final String collectionId;
  List<Map<String, dynamic>> items = [];
  List<Map<String, dynamic>> filteredItems = [];
  List<String> categories = [
    'Cat 1',
    'Cat 2',
    'Cat 3',
    'Cat 4',
    'Cat 5',
    'Cat 6'
  ];
  int selectedCategoryIndex = 0;
  int currentPage = 1;
  SharedPreferences? prefs;

  DataProvider({required this.database, required this.collectionId}) {
    init();
  }

  Future<void> init() async {
    prefs = await SharedPreferences.getInstance();
    await loadDataFromPrefs();
    await fetchData();
  }

  Future<void> saveDataToPrefs() async {
    final stringList = items.map((item) => json.encode(item)).toList();
    await prefs?.setStringList('items', stringList);
  }

  Future<void> loadDataFromPrefs() async {
    final savedData = prefs?.getStringList('items');
    if (savedData != null) {
      items = savedData
          .map((item) => json.decode(item))
          .cast<Map<String, dynamic>>()
          .toList();
      filterItemsByCategory(categories[selectedCategoryIndex]);
      notifyListeners();
    }
  }

  void filterItemsByCategory(String category) {
    filteredItems = items
        .where(
            (item) => item['category'].toLowerCase() == category.toLowerCase())
        .toList();
  }

  void setSelectedCategoryIndex(int index) async {
    selectedCategoryIndex = index;
    await fetchData();
  }

  Future<void> fetchData() async {
    print('Fetching data');
    final category = categories[selectedCategoryIndex];
    print('Selected category: $category');

    // Indien een specifieke categorie is geselecteerd (d.w.z. niet 'Algemeen'), voeg een filter toe
    Map<String, dynamic> filters = {};
    if (selectedCategoryIndex != 0) {
      filters = {
        'category': {
          '\$eq': category,
        },
      };
    }

    final response = await database.listDocuments(
      collectionId: 'posts',
      databaseId: 'app',
    );

    final documents = response.documents;

    items.clear();

    items.addAll(documents.map((doc) {
      final decodedTitle = utf8.decode(base64.decode(doc.data['title']));
      final decodedContent = utf8.decode(base64.decode(doc.data['content']));

      return {
        ...doc.data,
        'title': decodedTitle,
        'content': decodedContent,
      };
    }));

    print('Items: $items');

    currentPage++;

    await saveDataToPrefs();

    // Update filteredItems after fetching data
    filterItemsByCategory(category);

    notifyListeners(); // Notify listeners after updating filteredItems
  }
}

在NewsScreen小部件中,我使用DataProvider根据所选类别显示和筛选项目。但是,当我选择一个类别时,过滤似乎对显示的项目没有任何影响。filteredItems列表仍为空。
我已经验证了项目列表具有正确的数据,并且正在使用正确的类别值调用filterItemsByCategory方法。但由于某种原因,过滤器不起作用。
我在实施过程中遗漏了什么吗?有没有更好的方法来过滤项目使用Provider?
任何帮助或指导都将不胜感激。谢谢你!

hts6caw3

hts6caw31#

修好了
将fetchData()更改为

Future<void> fetchData() async {
  print('Fetching data');
  final category = categories[selectedCategoryIndex];
  print('Selected category: $category');

  final response = await database.listDocuments(
    collectionId: 'posts',
    databaseId: 'app',
    queries: [
      Query.equal('category', [categories[selectedCategoryIndex]]),
    ],
  );

  final documents = response.documents;

  items.clear();

  documents.forEach((document) {
    final decodedTitle = utf8.decode(base64.decode(document.data['title']));
    final decodedContent = utf8.decode(base64.decode(document.data['content']));

    final transformedDocument = {
      ...document.data,
      'title': decodedTitle,
      'content': decodedContent,
    };

    items.add(transformedDocument);
  });

  print('Items: $items');

  currentPage++;

  // await saveDataToPrefs();

  // Update filteredItems after fetching data
  filterItemsByCategory(category);

  notifyListeners(); // Notify listeners after updating filteredItems
}

欢迎任何关于代码的好建议!

相关问题