Reputation: 21
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 ?
Upvotes: 2
Views: 318
Reputation: 363
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();
Upvotes: 1