error "Try replacing the reference to the instance member with a different "

Viewed 7316

Error:

The instance member 'userId' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expressiondartimplicit_this_reference_in_initializer

Problem that I am facing: i want to inialise user uid(i.e userId.uid) to profileId in the nav.dart so that i can use widget.profileId in profile page to show current user details in profile page .But i am getting the above error .

Please help me out :)

Thank you

this is nav.dart

.
.
import 'package:justpoll/screens/home_page/home.dart';
import 'package:justpoll/screens/trending.dart';
import 'package:justpoll/screens/profile/profile_page.dart';

class Nav extends StatefulWidget {
  @override
  _NavState createState() => _NavState();
}

class _NavState extends State<Nav> {
  UserModel userId;
  int _selectedIndex = 0;
  List<Widget> _widgetOptions = <Widget>[
    Home(),
    Trending(),
    CreatePoll(),
    // ChatHomeScreen(),
    ProfilePage(profileId: userId.uid),
  ];
.
.
.

And this is ProfilePage.dart

.
.
import 'package:justpoll/screens/profile/edit_profile.dart';
import 'package:justpoll/Constants.dart';

class ProfilePage extends StatefulWidget {
  final String profileId;

  ProfilePage({this.profileId});

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  FirebaseAuth auth = FirebaseAuth.instance;
.
.
2 Answers

It simply means that you can't assign one field to another directly.

To solve this there are several solutions:

Transform your variables into static variables

 static  UserModel userId; //here 
 static int _selectedIndex = 0;
 List<Widget> _widgetOptions = <Widget>[
    Home(),
    Trending(),
    CreatePoll(),
    // ChatHomeScreen(),
    ProfilePage(profileId: userId.uid),
  ];

or

Assign their value in the initState function (Best solution for StateFulWidget)

 UserModel userId; //here
  int _selectedIndex = 0;
  List<Widget> _widgetOptions;
  @override
  void initState() {
    List<Widget> _widgetOptions = <Widget>[
      Home(),
      Trending(),
      CreatePoll(),
      // ChatHomeScreen(),
      ProfilePage(profileId: userId.uid),
    ];
    super.initState();
  }

The above error occurs because you declare your variable userId directly inside the class and you are trying to initialize a non-static variable to profileId. Because you are using StatefulWidget, try initializing it inside your initState() method.

UserModel userId;
int _selectedIndex = 0;
List<Widget> _widgetOptions;

void initState() {
    super.initState();
    _widgetOptions = <Widget>[
      Home(),
      Trending(),
      CreatePoll(),
      // ChatHomeScreen(),
      ProfilePage(profileId: userId.uid),
    ];
}
Related