如何在Firebase中循环遍历数组? [英] How can I loop over an array in firebase?

查看:65
本文介绍了如何在Firebase中循环遍历数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Firebase获取数据.但是我对此有点挣扎,这就是现在的样子

Im trying to get data from firebase. But im a bit struggling with that heres how it looks now

getusers() async {
    var firestore = FirebaseFirestore.instance;
    List listOfIds = [];

  QuerySnapshot qn=  await firestore
        .collection('videos')
        .get()
        .then((QuerySnapshot querySnapshot) {
      querySnapshot.docs.forEach((doc) {
        setState(() {
         
         
        });
      });
    });

    if (!mounted) return;
    _allResults =qn.docs;

我想要的是获取hashtasg数组字段,然后将其添加到_allresults中的qn.doc数据中.但是我该怎么做呢?这是我的火力基地,因此您可以看到它的外观

What I want is get the hashtasg array field and then add it to the qn.doc data in _allresults . But how can I do that ? Heres my firebase so you can see how it looks

最后一步,我想遍历how叫主题标签数组

And last step I wanna loop over the howle hashtag array

这是我的小部件

 class Openalldocs extends StatefulWidget {
  final TextEditingController searchinginput;
  static const route = '/openalldocs';

  const Openalldocs({Key key, this.searchinginput}) : super(key: key);

  @override
  _OpenalldocsState createState() => _OpenalldocsState();
}

class _OpenalldocsState extends State<Openalldocs> {
  List _allResults = [];
  List _resultsList = [];
  Future resultsLoaded;
  bool nosuerfound = false;
  String searchresult;

  @override
  void initState() {
    super.initState();
    widget.searchinginput.addListener(_onsearchChanged);
    setState(() {
      nosuerfound = true;
    });
  }

  @override
  void dispose() {
    widget.searchinginput.removeListener(_onsearchChanged());

    super.dispose();
  }

  @override
  void didChangeDependencies() {
    widget.searchinginput.text;
    resultsLoaded = getusers();
    super.didChangeDependencies();
  }

  _onsearchChanged() {
    setState(() {
      nosuerfound = false;
    });
    searchResults();
  }

  searchResults() {
    var showResults = [];
    if (widget.searchinginput.text != "") {
      for (var tripsnapshot in _allResults) {
        var title = DatbaseService.instance
            .videosfromsnapshot(tripsnapshot)
            .hashtag1
            .toLowerCase();
        var title2 = DatbaseService.instance
            .videosfromsnapshot(tripsnapshot)
            .hashtag2
            .toLowerCase();
        var title3 = DatbaseService.instance
            .videosfromsnapshot(tripsnapshot)
            .hashtag3
            .toLowerCase();
        if (title.contains(widget.searchinginput.text.toLowerCase()) ||
            title2.contains(widget.searchinginput.text.toLowerCase()) ||
            title3.contains(widget.searchinginput.text.toLowerCase())) {
          setState(() {
            nosuerfound = true;
          });
          showResults.add(tripsnapshot);
        }
      }
    } else {
      setState(() {
        nosuerfound = true;
      });
      showResults = List.from(_allResults);
    }
    setState(() {
      _resultsList = showResults;
    });
  }

  getusers() async {
    var firestore = FirebaseFirestore.instance;
    List listOfIds = [];
 QuerySnapshot qn=  await firestore
        .collection('videos')
        .get()
        .then((QuerySnapshot querySnapshot) {
      querySnapshot.docs.forEach((doc) {
        setState(() {
                       _allResults.add(doc.data()["hashtag1"]);         

         
        });
      });
    });

    if (!mounted) return;

    searchResults();
    return "Complete";
  }

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<Userforid>(context);
    if (nosuerfound == true) {
      return ListView.builder(
          itemCount: _resultsList.length,
          itemBuilder: (BuildContext context, int index) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // the AMOUNT is how many hashtags you want to show
                for (var i = 0; i < _resultsList.length; i += 1) ...[
                  // the SizedBox will only exist between the elements in the list
                  // as before
                  if (i != 0) SizedBox(height: 6),
                  // create a builder to allow declaring a variable
                  Builder(
                    builder: (context) {
                      // declare the hashtag variable
                      final hashtag = 'hashtag${i + 1}';

                      return InkWell(
                        onTap: () {
                          // do something with the hashtag stored in the variable
                          // this will make it relative to the element in the list
                        },
                        child: Column(
                          children: <Widget>[
                            // why is there a Column inside another with only one child?
                            // I would recommend to remove it
                            Column(
                              children: [
                                HighlightedMatchesText(
                                  searchString: widget.searchinginput.text,
                                  // notice how I am using the hashtag variable here
                                  // instead of a constant? ('hashtag1'), by the way
                                  // the for loop will make the hashtag start at 0
                                  // you can change it by increment in the declaration
                                  // `final hashtag = 'hashtag${i+1}'`, if you want
                                  // the existing behavior
                                  content: _resultsList[index][hashtag],
                                ),
                              ],
                            ),
                            // what is this? if it is to add more space between the items
                            // in the list, I recommend removing it from here, and add it
                            // to the first `SizedBox` in the for loop
                            // in case you do that, the Column that this widget belong
                            // would also only now contain one widget, so, there is no
                            // need to have it
                            SizedBox(height: 3),
                          ],
               
       

推荐答案

您正确使用了Firestore方法, querySnapshot.docs 是该集合中您正在循环浏览的所有文档的数组使用 forEach -您只需要在 doc.data()上添加更多逻辑.

You are using the Firestore methods correctly, the querySnapshot.docs is an array of all documents in that collection that you are looping through with forEach - You only require further logic on the doc.data().

在这种情况下:将所有"hashtag1" 推入结果

in this case: push all "hashtag1" to the results

.then((QuerySnapshot querySnapshot) {
          querySnapshot.docs.forEach((doc) {
            setState(() {
              _allResults.add(doc.data()["hashtag1"]);         
            });
          });

更新建议的代码块

Future<String> getusers() async {
    var firestore = FirebaseFirestore.instance;
    List listOfIds = [];
 QuerySnapshot qn=  await firestore
        .collection('videos')
        .get();
for (var doc in qn.docs) {
   setState(() {
                       _allResults.add(doc.data()["hashtag1"]);
        });
}
      });
    });

    if (!mounted) return "Error loading";

    searchResults();
    return "Complete";
  }

这篇关于如何在Firebase中循环遍历数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆