1

How can I retrieve a data from firebase database with Timer function in flutter app?

P.S.After user request data will be retrieved from firebase database 5 minutes later.

Thank you

7 Answers7

0
  Future.delayed(Duration(minutes: 5), () {
      Timer.periodic(Duration(minutes: 5), (Timer t) {
        setState(() {});
      });
    });

okay put this in the stateful widget with you StreamBuilder this worked on my emulator. Let me know if it works for you.

wcyankees424
  • 2,554
  • 2
  • 12
  • 24
  • Unfortunately it did not work. You could see my code below –  Apr 09 '20 at 21:30
  • 1
    I got something different for you to try – wcyankees424 Apr 09 '20 at 23:37
  • Yes it worked but not in the way that I want. Actually at the beginning I dont want to see any posts which retrieved from firebase database (plank page). After the request of user timer will work and will not retrieve data again automatically 5 minutes later. The aim is retrieving data with user request after the 5 minutes of the request. There will be no any data retrive till the new request of the user :) It will not be periodic.Thank you very much again for your kind support! Waiting for your answer... –  Apr 10 '20 at 10:02
  • Are you going to check my request? –  Apr 10 '20 at 14:28
  • 1
    i changed it it is not the same it is very similar but i wrapped it in a ```Future.delayed``` – wcyankees424 Apr 10 '20 at 14:29
  • Ok it is working. Thank you. How can I retrive only 1 document from firebase because with my code it shows all the docs. I would like to show only one document after user request... –  Apr 10 '20 at 14:49
  • 1
    ill add it in another answer if you don't mind just upvote it so i can get some points for the extra help – wcyankees424 Apr 10 '20 at 14:58
0

My code is just like below but it did not work with your code.@wcyankees424

body: StreamBuilder(
        stream: qs.collection('collection').snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            const Text('Loading');
            return Center(
              child: CircularProgressIndicator(),
            );
          } else {
            return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (context, index) {
                  List<DocumentSnapshot> listedQS = snapshot.data.documents;
                  var random = new Random();
                  for (var i = listedQS.length - 1; i > 0; i--) {
                    var n = random.nextInt(i + 1);
                    var temp = listedQS[i];
                    listedQS[i] = listedQS[n];
                    listedQS[n] = temp;
                  }

                  DocumentSnapshot mypost = listedQS[0];
0
 Future<void> addEntry(Brew newBrew) async {
    //value you want saved are stored in newBrew and passed in
    Map<String, Object> entryData = {
      'name': newBrew.name,
      'strength': newBrew.strength,
      'sugars': newBrew.sugars,
      'index': newBrew.index,
    };
    await Firestore.instance.collection('//collection name').add(entryData);
  }

 Future<Brew> getEntries(Brew newBrew) async {
    QuerySnapshot snapshot = await Firestore.instance
        .collection('//Collection name')
        .where('index', isGreaterThanOrEqualTo: Random().nextInt('//this number should be higher than the number of documents'))
        .orderBy('index')
        .limit(1)
        .getDocuments();

    if (snapshot.documents.isNotEmpty) {
      Map<String, dynamic> documentData = snapshot.documents[0].data;

      return Brew(
        strength: documentData['strngth'],
        sugars: documentData['sugars'],
        name: documentData['name'],
        index: documentData['index'],
      );
    } else {
      snapshot = await Firestore.instance
          .collection('//Collection name')
          .where('index', isGreaterThanOrEqualTo: 0)
          .orderBy('index')
          .limit(1)
          .getDocuments();

      Map<String, dynamic> documentData = snapshot.documents[0].data;

      return Brew(
        strength: documentData['strngth'],
        sugars: documentData['sugars'],
        name: documentData['name'],
        index: documentData['index'],
      );
    }
  }

class Brew {
  final String name;
  final String sugars;
  final int strength;
  final int index;

  Brew({
    this.name,
    this.sugars,
    this.strength,
    this.index,
  });
}

you would create and field for every called index which would start at 0 increment by 1 for every entry in your in your database. This might help you

wcyankees424
  • 2,554
  • 2
  • 12
  • 24
  • I would like to ask you something else. I have 100 docs in my database. I would like to retriew 1 document randomly to unique user. I mean if the same user request to retrieve doc the code will choose and retrieve the data from remaining 99 documents. How can I achieve this? –  Apr 10 '20 at 15:07
  • Unfortunately no –  Apr 10 '20 at 15:23
  • 1
    can you press the up arrow on the answers please the answer button just switches the answer. I also updated my answer – wcyankees424 Apr 10 '20 at 15:48
  • Thank you. I will try this –  Apr 10 '20 at 15:50
  • How can I implement it? Could you please share a whole code in order to understand more clearly? I am not professional like you :) –  Apr 10 '20 at 19:19
  • 1
    i added some more code I made a example class you would obviously substitute in your own I hope this clear things up for you. – wcyankees424 Apr 10 '20 at 20:02
  • Thanks for your kind support! I will try it :) –  Apr 10 '20 at 20:03
  • Did you check my below post? I need your support! Thank you –  Apr 11 '20 at 16:30
0

My code is like below how could I show text and image values with Querysnapshot method ? That you've mentioned with brew code! I cant use your code with below code structure...

Your code: @wcyankees424

   snapshot = await Firestore.instance
      .collection('//Collection name')
      .where('index', isGreaterThanOrEqualTo: 0)
      .orderBy('index')
      .limit(1)
      .getDocuments();

my code:

body: StreamBuilder(
        stream: qs.collection('collection').limit(1).snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            const Text('Loading');
          } else {
            return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (context, index) {
                  List<DocumentSnapshot> listedQS =
                      snapshot.data.documents; //listed documents
                  var random = new Random(); //dart math
                  for (var i = listedQS.length - 1; i > 0; i--) {
                    var n = random.nextInt(i + 1);
                    var temp = listedQS[i];
                    listedQS[i] = listedQS[n];
                    listedQS[n] = temp;
                  }
                  DocumentSnapshot mypost = listedQS[0];
                  return Stack(
                    children: <Widget>[
                      Container(
                        width: MediaQuery.of(context).size.width,
                        height: 350,
                        child: Padding(
                          padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
                          child: Material(
                            color: Colors.white,
                            elevation: 14.0,
                            shadowColor: Color(0x882196F3),
                            child: Center(
                              child: Padding(
                                padding: EdgeInsets.all(8.0),
                                child: Column(
                                  children: <Widget>[
                                    Container(
                                      width:
                                          MediaQuery.of(context).size.width,
                                      height: 200,
                                      child: Image.network(
                                          '${mypost['image']}',
                                          fit: BoxFit.fill),
                                    ),
                                    SizedBox(height: 10.0),
                                    Text(
                                      '${mypost['title']}',
                                      style: TextStyle(
                                          fontSize: 20.0,
                                          fontWeight: FontWeight.bold),
                                    ),
                                    SizedBox(height: 10.0),
                                    Text(
                                      '${mypost['subtitle']}',
                                      style: TextStyle(
                                          fontSize: 16.0,
                                          fontWeight: FontWeight.bold,
                                          color: Colors.blueGrey),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
0
@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: StreamBuilder(
            stream: Firestore.instance.collection('fortunepool').where('index', isGreaterThanOrEqualTo: 0).orderBy('index').limit(1).snapshots(),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return Container(child: CircularProgressIndicator());
              } else {
                return ListView.builder(
                    itemCount: snapshot.data.documents.length,
                    itemBuilder: (context, index) {
                      List<DocumentSnapshot> listedQS =
                          snapshot.data.documents; //listed documents
                      var random = new Random(); //dart math
                      for (var i = listedQS.length - 1; i > 0; i--) {
                        var n = random.nextInt(i + 1);
                        var temp = listedQS[i];
                        listedQS[i] = listedQS[n];
                        listedQS[n] = temp;
                      }
                      DocumentSnapshot mypost = listedQS[0];
                      return Stack(
wcyankees424
  • 2,554
  • 2
  • 12
  • 24
  • Actually my code is working but I have problem with random selection. When I put limit as 1 it only shows the first document from database and it does not change with time. As I have mentioned before I have 100 docs in my database. I would like to retriew 1 document randomly to unique user. I mean if the same user request to retrieve doc the code will choose and retrieve the data from remaining 99 documents. I did not achieve only one retrieve but after second request it did not show the first document any more it will show only one document from remaining documents from the database –  Apr 11 '20 at 21:35
  • 1
    that is because you need to use an index with a where query – wcyankees424 Apr 11 '20 at 21:47
  • How can I do that? I created below query in a seperate dart page but it is difficult to implement my home page. I edited above code –  Apr 11 '20 at 21:47
  • 1
    when you add entries to your database use something similar to the ```addEntry``` function above so every document has a index starting at 0,1,2,3,... then your ```StreamBuilder``` would listen to ```Firestore.instance .collection('//Collection name') .where('index', isGreaterThanOrEqualTo: 0) .orderBy('index') .limit(1) .snapshots(),``` – wcyankees424 Apr 11 '20 at 22:01
  • Please check above code.I see only a blank screen. There is also random code in Listview is it correct? –  Apr 11 '20 at 22:11
  • 1
    Im sorry I must not be explaining this clearly the random number is to get the document from firebase after that you are done with it go through this again https://stackoverflow.com/questions/46798981/firestore-how-to-get-random-documents-in-a-collection – wcyankees424 Apr 11 '20 at 22:43
  • Actually when I add .where('index', isGreaterThanOrEqualTo: 0). it shows blank page on my emulator but when I delete it it shows the snapshot from database. What is the exact problem ? –  Apr 12 '20 at 09:37
  • 1
    thats probably because you haven't added an actual index to the items in firebase there has to be an index field in your document – wcyankees424 Apr 12 '20 at 15:32
  • 1
    why did you unaccept the answer below this is it not working for you now? – wcyankees424 Apr 12 '20 at 15:44
  • I corrected it! Could you please create a screenshot for firebase database structure? Is there any chat section that I could write to you in stackoverflow? –  Apr 12 '20 at 15:47
  • 1
    yes we should move to there we aren't really supposed to be having extended conversations in here I posted it – wcyankees424 Apr 12 '20 at 16:05
  • How can we reach each other? What is your recommendation? –  Apr 12 '20 at 16:11
  • 1
    Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/211489/discussion-between-wcyankees424-and-flutter-new-learner). – wcyankees424 Apr 12 '20 at 16:17
  • I am in chat now. Waiting for you!:) –  Apr 12 '20 at 16:34
  • Can you start chat session again? Thank you –  Apr 15 '20 at 19:44
  • I sent you email. Could you please check? –  Apr 15 '20 at 21:30
0

Hope this helps So what you are do by calling where('index' isEqualTo: ' 0' is it first finds any documents with a field named index like above then it only returns the ones the has a value this is equal to to the one you provided

wcyankees424
  • 2,554
  • 2
  • 12
  • 24
0

My code is just like below. I aso updated database as you've indicated above but still white screen

Widget build(BuildContext context) {
return Scaffold(
    body: StreamBuilder(
        stream: Firestore.instance
            .collection('fortunepool')
            .where('index', isGreaterThanOrEqualTo: 0)
            .orderBy('index')
            .limit(1)
            .snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Container(child: CircularProgressIndicator());
          } else {
            return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (context, index) {
                  List<DocumentSnapshot> listedQS =
                      snapshot.data.documents; //listed documents

                  DocumentSnapshot mypost = listedQS[0];
                  return Stack(