I am using MultiProvider Stream with a database service with the firebase calls and a data model and using to and fromJson.
I am calling the Firestore User in my main file, and have a wrapper to call the user's document which holds the reference to the company they belong to, once the user data is retrieved we then call the company document in a userType screen, I then use the reference and pass it to the getter of the company document, but the document is being called before the document ref is passed.
I have tried to change the Stream to a Future but then I get an error on Provider.
Database Service
Stream<Companies> streamCompanies() {
_userRef.get().then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
print('HERE IS THE SNAPSHOT');
print(documentSnapshot.get('companyID'));
thisUserCompany = documentSnapshot.get('companyID');
}
});
debugPrint('Database Service => GETTING COMPANY STREAM');
debugPrint(thisUserCompany);
return _database
.collection('companies')
.doc(thisUserCompany)
.snapshots()
.map(
(snapshot) =>
Companies.fromJson(snapshot.data() as Map<String, dynamic>),
);
}
Comapnies Class
class Companies {
final String uid;
final String companyName;
final String logoForPDF;
Companies ({required this.uid, required this.companyName,
required this.logoForPDF});
Companies.fromJson(Map<String, dynamic> json)
: uid = json['uid'],
companyName = json['companyName'],
logoForPDF = json['logoForPDF'];
Map<String, dynamic> toJson() => {
'uid': uid,
'companyName': companyName,
'logoForPDF': logoForPDF,
};
factory Companies.initialData() {
return Companies(
uid: 'Loading',
companyName: 'Loading',
logoForPDF: 'Loading',
);
}
}
MultiProvider
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
final user = Provider.of<UserData?>(context);
return user != null
? MultiProvider(providers: [
StreamProvider<Companies?>.value(
initialData: Companies.initialData(),
value: user != null
? DatabaseService(uid: user.uid, companyID: user.companyID)
.streamCompanies()
: null),
], child: const ProfileSelector())
: const CircularProgressIndicator();
}
}
Ok so a little more perseverance I now have this working but I do not know if this is the correct way of doing this.
In my database file, I have changed the code to the following
Stream<Companies> streamCompanies() async* {
await _userRef.get().then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
thisUserCompany = documentSnapshot.get('companyID');
}
});
yield* _database
.collection('companies')
.doc(thisUserCompany)
.snapshots()
.map((snapshot) =>
Companies.fromJson(snapshot.data() as Map<String, dynamic>),
);
}
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.