0

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;

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 enter image description here

And last step I wanna loop over the howle hashtag array

This is my widget

 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),
                          ],
               
       
1
  • The _allResults is List right? Commented Apr 22, 2021 at 9:18

3 Answers 3

2

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().

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

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

Update Suggested code block

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";
  }
Sign up to request clarification or add additional context in comments.

4 Comments

it says then Class 'String' has no instance method 'data'. Receiver: "#xbxbd" Tried calling: data() The relevant error-causing widget was Builder lib/homesearchingall/openalldocs.dart:131
when I removing data() check code so you can see the widget pls
The resultlist has im setting equal to _allresults list just filtering it later
try removing the whole .then block since you are using await, this allows you to fetch qn.docs as your original code.
0

yea check out this. if any error, let me no because i am not on system

 List<QueryDocumentSnapshot> _allResults =[]
    
    QuerySnapshot qn = await firestore.collection('videos').get();
        if (!mounted) return;
    
        setState(() {
          _allResults = qn.docs;
        });

1 Comment

This giving all hashtags to the list
0

UPDATE

This line states that the _resultList is a List of documents, and you want to access all the hashtags from it, because you have the for-loop, which goes until it reaches the length of _resultList, therefore you are getting all the hashtags. If you only want to show the hashtag1, then change this:

content: _resultsList[index].data()[hashtag],

to this:

content: _resultsList[index].data()["hashtag1"],

If you want to have all the documents in this List, use this:

.then((QuerySnapshot querySnapshot) {
  _allResults = querySnapshot.docs;
}

16 Comments

The second method give no errors but again give all hashtags to the list and not only one the first give this error Class 'String' has no instance method 'data'. Receiver: "#xbxbd" Tried calling: data() The relevant error-causing widget was Builder lib/homesearchingall/openalldocs.dart:131
Then it says type 'String' is not a subtype of type 'int' of 'index' The relevant error-causing widget was Builder lib/homesearchingall/openalldocs.dart:131
The resultlist has im setting equal to _allresults list just filtering it later
giving the same error again first the error Class 'String' has no instance method '..... and then when removing data() 'String' is not a subtype of type 'int' of 'index' . I understand your idea but he problems is I implemented these hashtags in other region and because of that it will be very hard to reformat all that code this will be my last last like last of last option
yes then It show me the error again as I said
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.