Reputation: 9
I build a drawer that contains friends requests and I would like to update it automatically when a new friend request is sent to my user.
I build this Drawer widget:
import 'package:flutter/material.dart';
import 'package:opinions/provider/user_provider.dart';
import 'package:opinions/user/user_model.dart';
import 'package:opinions/widgets/avatar_logo.dart';
import 'package:provider/provider.dart';
class FriendsRequestDrawer extends StatefulWidget {
static const String routeName = "friends_request_drawer";
const FriendsRequestDrawer({super.key});
@override
State<FriendsRequestDrawer> createState() => _FriendsRequestDrawerState();
}
class _FriendsRequestDrawerState extends State<FriendsRequestDrawer> {
late Stream<List<UserAccount>> userStream;
@override
void initState() {
super.initState();
userStream = Provider.of<UserProvider>(context, listen: false).getFindsRequestsAccountsStream();
}
@override
Widget build(BuildContext context) {
return Drawer(
child: StreamBuilder<List<UserAccount>>(
stream: userStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(child: Text("Error: ${snapshot.error}"));
}
final userAccount = snapshot.data ?? [];
if (userAccount.isEmpty) {
return Center(child: Text("No Find Requests"));
}
return ListView.builder(
itemCount: userAccount.length,
itemBuilder: (context, index) {
return ListTile(
leading: AvatarLogo(
onPressed: () {},
width: 30,
height: 30,
border: null,
backgroundImage: userAccount[index].photoURL == null
? null
: AssetImage(userAccount[index].photoURL!),
),
title: Text(userAccount[index].pseudo),
);
},
);
},
),
);
}
}
With these Stream functions:
Stream<List<UserAccount>> getFindsRequestsAccountsStream() async* {
if (userAccount != null && userAccount!.findsRequest.isNotEmpty) {
List<UserAccount> findsRequestsAccounts = [];
for (Map<String, String> element in userAccount!.findsRequest) {
try {
UserAccount newUser = await DbHelper
.getStreamUser(element['uid']!)
.first;
findsRequestsAccounts.add(newUser);
} catch (e) {
print('Error fetching user: $e');
}
}
yield findsRequestsAccounts;
} else {
yield [];
}
}
et cette fonction pour récupérer les données de ma database :
static Stream<UserAccount> getStreamUser(String uid) {
return FirebaseFirestore.instance
.collection(collectionUser)
.doc(uid)
.snapshots()
.map((snapshot) => UserAccount.fromJson(snapshot.data()!));
}
I don't understand why my data don't get refresh automatically in my drawer when I add (manually) a new friend request in my database. It only refreshes it when I leave and enter a new time in my drawer. Thanks for your help
Upvotes: 0
Views: 33