get Data from different Collections using Firebase and flutter and update the UI when data changes

124

You have written get query which will return data just once. For getting updates for changes use snapshot query. It will return list of documents when there is any change.

Change your Second Query as below for customer details updates:

var providerDocument = await FirebaseFirestore.instance
          .collection("collectionName")
          .doc(abbonierten.elementAt(j))
          .snapshots();

If you want to get updates for customer documents too, change first query as below :

var customerDocument = await FirebaseFirestore.instance
        .collection("XXXX")
        .doc(user.uid)
        .snapshots();
Share:
124
Frank van Puffelen
Author by

Frank van Puffelen

I am an engineer for Firebase at Google. I respond equally well to being called "Frank" or "puf".

Updated on December 29, 2022

Comments

  • Frank van Puffelen
    Frank van Puffelen over 1 year

    i'm developing an app with flutter and i have some difficultes. i used the follow function with Streambuilder to get data from two collections but the UI doesn't update when data changes in firebase. here my function :

    class MyHomePage extends StatefulWidget {
      const MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      List<Post> listStream = [];
      AuthenticationService service = AuthenticationService();
      Stream<List<Post>> fetch() async* {
        User user = service.getCurrentUser();
        var customerDocument = await FirebaseFirestore.instance
            .collection("XXXX")
            .doc(user.uid)
            .get();
    
        List<String> abbonierten =
            List<String>.from(customerDocument["EEEE"]);
        for (int j = 0; j < abbonierten.length; j++) {
          var providerDocument = await FirebaseFirestore.instance
              .collection("WWWWW")
              .doc(abbonierten.elementAt(j))
              .get();
          List<Map> posts = List<Map>.from(providerDocument["posts"] ?? []);
          for (int item = 0; item < posts.length; item++) {
            Post post =
                Post.fromJson(providerDocument.data(), posts.elementAt(item));
            listStream.add(post);
          }
        }
        yield listStream;
      }
      StreamChatList streamChatList = StreamChatList();
      ChatService chatService = ChatService();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Kindacode.com'),
          ),
          body: Padding(
            padding: const EdgeInsets.all(30),
            child: StreamBuilder(
              stream: fetch(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  List<Post> data = snapshot.data;
                  return ListView.builder(
                      itemCount: data.length,
                      itemBuilder: (context, index) {
                        return Text(data.elementAt(index).title);
                      });
                }
                return Center(child: LinearProgressIndicator());
              },
            ),
          ),
        );
      }
    }
    
    
    

    or is there another method to achieve this task. can someome help me with it pls ?

    • Frank van Puffelen
      Frank van Puffelen almost 3 years
      You're calling get() on Firestore, which reads values only once. If you want to listen for realtime updates, use the snapshots() method instead. Also see firebase.flutter.dev/docs/firestore/usage#realtime-changes
    • Admin
      Admin almost 3 years
      thank you for your answer. but how can use snapshots outside Streambuilder instead get() ?
  • Admin
    Admin almost 3 years
    thank you for your answer, but how i can use Stream outside Streambuilder ?
  • fabc
    fabc almost 3 years
    @Akram could you elaborate on your question? It's a little confusing since my sparse knowledge on Dart and the introductory video on flutter.dev have lead me to believe that Streambuilder is Flutter's equivalent to Stream, how and why would you want to use the Stream class outside of StreamBuilder?
  • Admin
    Admin almost 3 years
    i mean , how can i get more than one collection and i want to get data inside a function outside Streambuilder.
  • Admin
    Admin almost 3 years
    show my function fetch() , i want to use snapshots instead get()
  • fabc
    fabc almost 3 years
    @Akram do you mean the .data() function? And your second comment seems out of context, it might just be that I'm a little sleepy and therefore slow on the up-take.