Flutter 过滤器 Firebase 数据库

时间:2021-02-14 10:13:13

标签: flutter firebase-realtime-database

{
  "story" : {
    "-MTOpnFnINch-hCT4tG7" : {
      "creatorId" : "KEieXFzt9zezgP9684EhCxRNzp42",
      "img" : "https://www.petyourdog.com/uploads/breed_lists/Toy-Dog-Breeds.jpg",
      "story" : "111111111111333333333333333333333333333333333333333333333333222222222",
      "title" : "111111111111111111"
    },
    "-MTOq-_X96CLJ6-v6WFx" : {
      "creatorId" : "EJW4BU1IRMUtchW1bzUPmeLzttZ2",
      "img" : "https://naturaldogcompany.com/wp-content/uploads/2016/03/shutterstock_194843813-web-180x180.jpg",
      "story" : "qqqqqqqqqqqqwwwwwwwwwwwwwwwwwqwwwwww",
      "title" : "qqqqqqqq"
    },
    "-MTP0N2MkCj44I7aPudf" : {
      "creatorId" : "KEieXFzt9zezgP9684EhCxRNzp42",
      "img" : "https://naturaldogcompany.com/wp-content/uploads/2016/03/shutterstock_194843813-web-180x180.jpg",
      "story" : "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk",
      "title" : "yyyyykkkkkkkkkkkkkkkk"
    },
    "-MTUgGBHkcnOBCMmToGU" : {
      "creatorId" : "KEieXFzt9zezgP9684EhCxRNzp42",
      "img" : " ",
      "story" : "qqqqqqqqqqqqqqqqqqqqqqqwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqq",
      "title" : "ooooooooooooo"
    }
  },
  "userFavorites" : {
    "KEieXFzt9zezgP9684EhCxRNzp42" : {
      "-MTOq-_X96CLJ6-v6WFx" : true
    }
  }
}


这是我正在处理的数据。我试图过滤用户故事页面上的数据,其中只显示用户自己的数据。

代码如下:


  class Stories with ChangeNotifier {
  List<Story> _storys = [
    
  ];

  final String authToken;
  final String userId;

  Stories(this.authToken, this.userId, this._storys);



  List<Story> get storys {

    return [..._storys];
  }

  List<Story> get favoriteItems {
    return _storys.where((storyItem) => storyItem.isFavorite).toList();
  }

  Story findById(String id) {
    return _storys.firstWhere((story) => story.id == id);

  }

  Future<void> fetchAndSetProducts([bool filterByUser = false]) async {
    final filterString = filterByUser ? 'orderBy="creatorId"&equalTo="$userId"' : '';
    var url =
        'https://unified-adviser--#####..firebaseio.com/story.json?auth=$authToken&$filterString';
    try {
      final response = await http.get(url);
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      if (extractedData == null) {
        return;
      }
      url =
          'https://unified-adviser-#####.firebaseio.com/userFavorites/$userId.json?auth=$authToken';
      final favoriteResponse = await http.get(url);
      final favoriteData = json.decode(favoriteResponse.body);
      final List<Story> loadedProducts = [];
      extractedData.forEach((prodId, prodData) {
        loadedProducts.add(Story(
          id: prodId,
          title: prodData['title'],
          story: prodData['story'],
          // price: prodData['price'],
          isFavorite:
              favoriteData == null ? false : favoriteData[prodId] ?? false,
          img: prodData['img'],
        ));
      });
      _storys = loadedProducts;
      notifyListeners();
    } catch (error) {
      throw (error);
    }
  }
.
.
.
.

  

用户故事页面,我正在尝试过滤数据

class UserStory extends StatelessWidget {
  static const routeName = 'userStory';
  
  Future<void> _refreshProducts(BuildContext context) async {
    await Provider.of<Stories>(context, listen: false)
        .fetchAndSetProducts(true);
  }

  @override
  Widget build(BuildContext context) {
    print('rebuilding...');
    return Scaffold(
      appBar: AppBar(
        title: const Text('Your Products'),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              Navigator.of(context).pushNamed(EditStoryScreen.routeName);
            },
          ),
        ],
      ),
      // drawer: AppDrawer(),
      body: FutureBuilder(
        future: _refreshProducts(context),
        builder: (ctx, snapshot) =>
            snapshot.connectionState == ConnectionState.waiting
                ? Center(
                    child: CircularProgressIndicator(),
                  )
                : RefreshIndicator(
                    onRefresh: () => _refreshProducts(context),
                    child: Consumer<Stories>(
                      builder: (ctx, productsData, _) => Padding(
                            padding: EdgeInsets.all(8),
                            child: ListView.builder(
                              itemCount: productsData.storys.length,
                              itemBuilder: (_, i) => Column(
                                    children: [
                                      UserStoryItem(
                                        productsData.storys[i].id,
                                        productsData.storys[i].title,
                                        productsData.storys[i].img,
                                      ),
                                      Divider(),
                                    ],
                                  ),
                            ),
                          ),
                    ),
                  ),
      ),
    );
  }
}

我使用的方法不起作用,即使我使用新帐户注册我也可以查看UserStory页面中的所有数据并编辑或删除它们!

这里有什么问题?

1 个答案:

答案 0 :(得分:0)

我可以看到过滤器字符串是错误的。您可以使用以下内容。但是,如果它不起作用,您可能需要使用 Firebase RTDB 包。

final filterString = filterByUser ? 'orderBy=\"creatorId\"&equalTo=\"$userId\"' : '';
相关问题