0

Hoping someone can help me with this. I have a StreamProvider which works great with this:

class DatabaseService {
  final String uid;
  DatabaseService({this.uid});

  final Query flashCardWordsCollection = Firestore.instance.collection('MyWords')
      .where("SelectedToStudy", isEqualTo: true)
      .where("DocBelongsTo", isEqualTo: "rgDe5I0QgFfax123Igxo8VQew9T2")
      .orderBy("LastFlashCard", descending: false);

However, I need to change the DocBelongsTo filter to be based on the user that is currently logged into the app. When I try this:

class DatabaseService {
  final String uid;
  DatabaseService({this.uid});

  final Query flashCardWordsCollection = Firestore.instance.collection('MyWords')
      .where("SelectedToStudy", isEqualTo: true)
      .where("DocBelongsTo", isEqualTo: uid)
      .orderBy("LastFlashCard", descending: false);

Where on the home_screen.dart I called the StreamProvider like this:

final user = Provider.of<User>(context);

return StreamProvider<List<VoBuWord>>.value(
  value: DatabaseService(uid: user.uid).flashCardWords ,

I get an error of:

lib/services/database.dart:11:41: Error: Can't access 'this' in a field initializer to read 'uid'.
      .where("DocBelongsTo", isEqualTo: uid)

From the research I have been doing I understand it is due to the fact that uid may or may not have been set when this is called, therefore I get the error. But I have no idea how to fix this.

Users are not able to use the app without signing in first so in theory the uid should never be blank, however, I don't know how to tell the class this.

Any help would be greatly appreciated.

Thanks

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
MSW
  • 31
  • 4

1 Answers1

1

You need to use a method or constructor to access instance fields of a class, for example:

Query getData(){
  return Firestore.instance.collection('MyWords')
      .where("SelectedToStudy", isEqualTo: true)
      .where("DocBelongsTo", isEqualTo: uid)
      .orderBy("LastFlashCard", descending: false);
  }

Then to call it just do:

Stream<List<VoBuWord>> get flashCardWords {
 return getData().snapshots().map(_vobuWordListFromSnapshot);
 } 
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • Thanks for the help, but I am still confused. How/where do I call the getData? The database.dart file is now: class DatabaseService { final String uid; DatabaseService({this.uid}); void getData(){ final Query flashCardWordsCollection = Firestore.instance.collection('vobuWords') .where("SelectedToStudy", isEqualTo: true) .where("DocBelongsTo", isEqualTo: uid) .orderBy("LastFlashCard", descending: false); } Stream> get flashCardWords { return flashCardWordsCollection.snapshots().map(_vobuWordListFromSnapshot); } – MSW Aug 19 '20 at 21:05
  • @MSW check my edit `return DatabaseService(uid : this.uid).getData().snapshots() – Peter Haddad Aug 19 '20 at 21:21
  • You need to create an instance of DatabaseService then you can call getdata – Peter Haddad Aug 19 '20 at 21:22