Home > database >  I am getting this error "The instance member 'widget' can't be accessed in an in
I am getting this error "The instance member 'widget' can't be accessed in an in

Time:08-02

This is my code :

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

class viewLossEvent extends StatefulWidget {
  String code,
      
  viewLossEvent(
      {this.code});

  @override
  State<viewLossEvent> createState() => _viewLossEventState();
}

class _viewLossEventState extends State<viewLossEvent> {

  int _selectedIndex = 0;

  void _navigateBottomBar(int index){
    setState(() {
      _selectedIndex = index;
    });
  }

  final List<Widget> _pages = [
    Container(
      child: Text(
          '${widget.code}'
      ),
    ),
  ];

the error that I am getting :

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

I am getting the error right here :

enter image description here

can anyone help solve this and kindly explain why this is happening.

Thank You!

CodePudding user response:

You cannot initialize a property by using widget.code. You should use initState instead :

List<Widget> _pages = [];

void initState() {
  super.initState();
  _pages = [
    Container(
      child: Text(
          '${widget.code}'
      ),
    ),
  ];
}

CodePudding user response:

Always prefer using getters instead fields because Flutter re-uses your state instance across the widget lifecycle and if you keep track the old object references you can face weird and hard to track bugs.

So use instead:

  List<Widget> get _pages => [
    Container(
      child: Text(
          '${widget.code}'
      ),
    ),
  ];

This also best fits the Flutter state management principles.

As you can see this getter will create a new instance of your Container widget every time you access the _pages field, this prevent us from accessing widgets that are not even in the screen anymore, and this approach has no performance issues since it just re-create the widget configuration.

In your case you can also fix the error by using the late modifier (Not recommended due the reasons mentioned above):

  late final List<Widget> _pages = [
    Container(
      child: Text(
          '${widget.code}'
      ),
    ),
  ];
  • Related