I'm using streamprovider to get firestore document's realtime changing data. (like a Streambuilder)
However when i change the data in firestroe consol while app is running, the widget does not reflect the changes. I searched it in stackoverflow whole day and i tried several answers in here, but it doesn't go on my code.
I'm wondering what is the problem!
class MainPage extends StatelessWidget {
DataProvider db = DataProvider();
@override
Widget build(BuildContext context) {
var userData = Provider.of<User?>(context);
return MultiProvider(
providers: [
StreamProvider<TUser>.value(
value: db.getUser(userData!.uid),
initialData: TUser(email: '', uid: '', name:'', registerdate: '', recentlogindate: '', istag: false, taglist:['index']),
updateShouldNotify: (_, __) => true,
),
StreamProvider<List<Note>>.value(
value: db.getNotes(userData.uid),
initialData: [],
),
ChangeNotifierProvider(
create: (BuildContext context) => SideBarProvider()),
],
child: MainPageSideBar()
);
}
}
class DataProvider extends ChangeNotifier {
final FirebaseFirestore _db = FirebaseFirestore.instance;
Stream<TUser> getUser(String uid) async* {
var snap = await _db.collection('users').doc(uid).get();
Map<String, dynamic>? user_data = snap.data();
yield TUser.fromMap(user_data);
}
Stream<List<Note>> getNotes(String uid) {
return FirebaseFirestore.instance.collection('users').doc(uid).collection('tags').snapshots()
.map((list) =>
list.docs.map((doc) => Note.fromMap(doc.data())).toList());
}
}
//usage
var noteDataList = Provider.of<List<Note>>(context);
I tried several things and then I found the solution. So, I answer myself. The problem was in DataProvider's getUser Method. Because of async function, I guess, Stream can't reflect the changes in database. Therefore, I changed method like this.
Stream<TUser> getUser(String uid) {
return FirebaseFirestore.instance.collection('users').doc(uid).snapshots().map((doc) => TUser.fromMap(doc.data()));
}
And now, my widget changes in realtime!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.