How do I construct this class in DART so that I use a required parameter to save/query?

0

Issue

I have a class called MessageDao that I’m going to use as the class that will handle all read/write/update operations with Firebase Realtime Database.

The desired outcome is that if I use this class anywhere in my app, I should be passing a groupIDPath string to it that will be used to locate the appropriate node in Realtime Database. From there, I should be able to read/write/update as needed.

I tried doing this below, but I get an error pointing to groupIDPath in the line where I’ve left a comment. The error says : The instance member 'groupIDPath' can't be accessed in an initializer. I read the documentation but I didn’t quite understand their example of the alternatives. Given what I am trying to accomplish here, how should I structure this class?

import 'package:firebase_database/firebase_database.dart';
import 'message.dart';

class MessageDao {

  MessageDao({required this.groupIDPath});

  String groupIDPath; //example = 'groupChats/0exUS3P2XKFQ007TIMmm'
  DatabaseReference _messagesRef = FirebaseDatabase.instance.reference().child(groupIDPath); //ERROR IS HERE

  //Get stream of messages from realtime database based on group ID

}

Solution

Assign _messagesRef in the initializer list:

import 'package:firebase_database/firebase_database.dart';
import 'message.dart';

class MessageDao {

  MessageDao({required this.groupIDPath}):
      _messagesRef = FirebaseDatabase.instance.reference().child(groupIDPath);

  String groupIDPath;
  DatabaseReference _messagesRef;
}

Answered By – mmcdon20

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More