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
}
CodePudding user response:
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;
}