I can’t work out what I’m doing wrong such that widget.event on line 15 is showing the mentioned error. I believe initState can fix it but I can’t for the life of me work out how I implement it.
class _EventDetailsScreenState extends State<EventDetailsScreen> {
final _database = FirebaseDatabase.instance;
final _eventRef = FirebaseDatabase.instance.reference().child('events/' + widget.event['eventId']);
The full code is below.
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
class EventDetailsScreen extends StatefulWidget {
final event;
EventDetailsScreen({Key? key, this.event}) : super(key: key);
@override
_EventDetailsScreenState createState() => _EventDetailsScreenState();
}
class _EventDetailsScreenState extends State<EventDetailsScreen> {
final _database = FirebaseDatabase.instance;
final _eventRef = FirebaseDatabase.instance.reference().child('events/' + widget.event['eventId']);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.event['eventName']),
),
body: StreamBuilder(
stream: _eventRef.onValue,
builder: (context, snapshot) {
if (snapshot.hasData) {
final event = snapshot.data!.snapshot.value as Map<String, dynamic>;
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Event Name: ' + event['eventName']),
Text('Event Date: ' + event['eventDate']),
Text('Event Time: ' + event['eventTime']),
Text('Event Location: ' + event['eventLocation']),
Text('Invited Users: ' + event['invitedUsers'].toString()),
],
),
);
} else {
return Center(child: Text('Loading'));
}
},
),
);
}
}
I tried to implement initState but I can’t seem to get it right, and nay adjustments I make seem to lead to more errors. It is my last error and it’s driving me crazy!
2
Answers
The error is on this line of code
You can’t use "widget" like that, but you can simply fix this by adding the "late" keyword
As an explanation: you can’t access the
widget
property inside of the constructor, or for initializing the members of the state object, because the state object is only mounted (connected to the widget) right before theinitState
method is called.The other answer from @jabguru is also an option with the inline
late final
initilizer, because the right side (the initialization) will only be called when the member variable is accessed the first time.