'The instance member 'loggedInUser' can't be accessed in an initializer [duplicate]
I am trying to use firebase for a flutter app I'm working on and when I get to the step of actually accessing the data in the database I'm encountering this weird error: "The instance member'loggedInUser' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression"
Code:
class _MainPageState extends State<MainPage> {
User? user = FirebaseAuth.instance.currentUser;
UserModel loggedInUser = UserModel();
@override
void initState() {
super.initState();
_performSingleFetch();
}
void _performSingleFetch() {
final database = FirebaseDatabase.instance
.ref('users')
.child(user!.uid)
.once()
.then((snapshot) {
final data = Map<dynamic, dynamic>.from(
snapshot.snapshot.value! as Map<dynamic, dynamic>);
loggedInUser = UserModel.fromJson(data);
});
}
List pages = [
HomePage(username: loggedInUser.firstName),
CommunityPage(),
InfoPage()
];
The error pops up in this section:
HomePage(username: loggedInUser.firstName),
Does anyone know how to fix the error?
Solution 1:[1]
You can't use any instance member(class attributes) for the initialization of any other instance member. So you need to declare pages as late List and inside initState you can initialize it. Here loggedInUser is an instance member and pages as well that is why you are getting the error. Update your code like the below one:-
class _MainPageState extends State<MainPage> {
User? user = FirebaseAuth.instance.currentUser;
UserModel loggedInUser = UserModel();
late List<Widget> pages;
@override
void initState() {
super.initState();
pages = [];
_performSingleFetch();
}
void _performSingleFetch() {
final database = FirebaseDatabase.instance
.ref('users')
.child(user!.uid)
.once()
.then((snapshot) {
final data = Map<dynamic, dynamic>.from(
snapshot.snapshot.value! as Map<dynamic, dynamic>);
loggedInUser = UserModel.fromJson(data);
pages = [
HomePage(username: loggedInUser.firstName??''),//you can have any default name here
CommunityPage(),
InfoPage()
];
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
