Aman Sharma
Aman Sharma

Reputation: 9

Flutter error: the instance 'widget' can't be accessed in an initializer

I'm getting this error while implementing agora ui kit. Error

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

import 'package:agora_uikit/agora_uikit.dart';

class LiveStream extends StatefulWidget {
  const LiveStream({
    Key key,
    this.width,
    this.height,
    this.channelname,
  }) : super(key: key);

  final double width;
  final double height;
  final String channelname;
  @override
  _LiveStreamState createState() => _LiveStreamState();
}

class _LiveStreamState extends State<LiveStream> {
  final AgoraClient client = AgoraClient(
    agoraConnectionData: AgoraConnectionData(
      appId: "--AppID--",
      channelName: widget.channelname,
    ),
  );

Upvotes: 0

Views: 70

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63549

A simple trick is using late keyword,

class _LiveStreamState extends State<LiveStream> {
  late final AgoraClient client = AgoraClient(
    agoraConnectionData: AgoraConnectionData(
      appId: "--AppID--",
      channelName: widget.channelname,
    ),
  );

Or you can use initState


class LiveStream extends StatefulWidget {
  const LiveStream({
    Key? key,
    required this.width,
    required this.height,
    required this.channelname,
  }) : super(key: key);

  final double width;
  final double height;
  final String channelname;
  @override
  _LiveStreamState createState() => _LiveStreamState();
}

class _LiveStreamState extends State<LiveStream> {
  late final AgoraClient client;

  @override
  void initState() {
    super.initState();
    client = AgoraClient(
      agoraConnectionData: AgoraConnectionData(
        appId: "--AppID--",
        channelName: widget.channelname,
      ),
    );
  }

Upvotes: 2

Related Questions