错误:无法在初始化程序中访问实例成员”widget”。

huangapple go评论70阅读模式
英文:

error: The instance member 'widget' can't be accessed in an initializer

问题

我不明白我在第15行上出了什么问题,以至于widget.event显示了提到的错误。我相信initState可以解决它,但我怎么也搞不清楚如何实现它。

class _EventDetailsScreenState extends State<EventDetailsScreen> {
  final _database = FirebaseDatabase.instance;
  final _eventRef = FirebaseDatabase.instance.reference().child('events/' + widget.event['eventId']);

完整的代码如下。

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'));
          }
        },
      ),
    );
  }
}

我尝试实现initState,但似乎无法搞定,我所做的任何调整似乎都会导致更多的错误。这是我的最后一个错误,正在让我疯狂!

英文:

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&lt;EventDetailsScreen&gt; {
  final _database = FirebaseDatabase.instance;
  final _eventRef = FirebaseDatabase.instance.reference().child(&#39;events/&#39; + widget.event[&#39;eventId&#39;]);

The full code is below.

import &#39;package:flutter/material.dart&#39;;
import &#39;package:firebase_database/firebase_database.dart&#39;;

class EventDetailsScreen extends StatefulWidget {
  final event;

  EventDetailsScreen({Key? key, this.event}) : super(key: key);

  @override
  _EventDetailsScreenState createState() =&gt; _EventDetailsScreenState();
}

class _EventDetailsScreenState extends State&lt;EventDetailsScreen&gt; {
  final _database = FirebaseDatabase.instance;
  final _eventRef = FirebaseDatabase.instance.reference().child(&#39;events/&#39; + widget.event[&#39;eventId&#39;]);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.event[&#39;eventName&#39;]),
      ),
      body: StreamBuilder(
        stream: _eventRef.onValue,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final event = snapshot.data!.snapshot.value as Map&lt;String, dynamic&gt;;
            return Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(&#39;Event Name: &#39; + event[&#39;eventName&#39;]),
                  Text(&#39;Event Date: &#39; + event[&#39;eventDate&#39;]),
                  Text(&#39;Event Time: &#39; + event[&#39;eventTime&#39;]),
                  Text(&#39;Event Location: &#39; + event[&#39;eventLocation&#39;]),
                  Text(&#39;Invited Users: &#39; + event[&#39;invitedUsers&#39;].toString()),
                ],
              ),
            );
          } else {
            return Center(child: Text(&#39;Loading&#39;));
          }
        },
      ),
    );
  }
}

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!

答案1

得分: 2

作为解释:您不能在构造函数内部访问widget属性,也不能在初始化状态对象的成员时访问它,因为状态对象只在initState方法调用之前挂载(连接到小部件)。

  late final DatabaseReference _eventRef;

  @override
  void initState() {
    super.initState();
    _eventRef = FirebaseDatabase.instance.reference().child('events/' + widget.event['eventId']);
  }

来自@jabguru的另一种选择是使用内联的late final初始化器,因为右侧(初始化)只有在首次访问成员变量时才会调用。

英文:

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 the initState method is called.


  late final DatabaseReference _eventRef;

  @override
  void initState() {
    super.initState();
    _eventRef = FirebaseDatabase.instance.reference().child(&#39;events/&#39; + widget.event[&#39;eventId&#39;]);
  }

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.

答案2

得分: 0

错误出现在这行代码上:

final _eventRef = FirebaseDatabase.instance.reference().child('events/' + widget.event['eventId']);

你不能像那样使用 "widget",但你可以通过添加 "late" 关键字来简单修复它:

late final _eventRef = FirebaseDatabase.instance.reference().child('events/' + widget.event['eventId']);
英文:

The error is on this line of code

final _eventRef = FirebaseDatabase.instance.reference().child(&#39;events/&#39; + widget.event[&#39;eventId&#39;]);

You can't use "widget" like that, but you can simply fix this by adding the "late" keyword

late final _eventRef = FirebaseDatabase.instance.reference().child(&#39;events/&#39; + widget.event[&#39;eventId&#39;]);

huangapple
  • 本文由 发表于 2023年7月14日 05:32:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683366.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定