Home > Back-end >  Accessing a variable from a Factory
Accessing a variable from a Factory

Time:09-17

I'm new to Flutter and Dart. I have a Stateful class with the _user variable. I'd like to use this variable in a query I'm making to Firestore. Neither "this" nor "_user" are available inside _usersStream (I believe this is a factory).

How can I access _user?

class _UserTermsState extends State<UserTerms> {
  late User _user;
  bool _isSigningOut = false;

  final Stream<QuerySnapshot> _usersStream = FirebaseFirestore.instance
      .collection('somecol')
      .where('uid', isEqualTo: this._user.uid)
      .orderBy('createdAt', descending: true)
      .snapshots();

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _usersStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {      
        return Scaffold( and so on...
      

CodePudding user response:

You can't access instance member '_user' in an initializer.

Try this:

class _UserTermsState extends State<UserTerms> {
  late User _user;
  bool _isSigningOut = false;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance
      .collection('somecol')
      // make sure _user is defined before build is called.
      .where('uid', isEqualTo: _user.uid)
      .orderBy('createdAt', descending: true)
      .snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
  • Related