简体   繁体   中英

Flutter filter firebase 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
    }
  }
}


This is the data I'm working on. Im trying to filter the data on the user story page, where only the user own data are shown.

Here the code:


  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);
    }
  }
.
.
.
.

  

the user story page, where I'm trying to filter the data

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(),
                                    ],
                                  ),
                            ),
                          ),
                    ),
                  ),
      ),
    );
  }
}

the method that Im using is not working, even when I do sign up with a new account I can view all the data in the UserStory page and edit or delete them!

What is the problem here?

I can see that the filter string is wrong. You can use the following. However, if it doesn't work, you might want to use the Firebase RTDB package.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM