nzxcvbnm
nzxcvbnm

Reputation: 184

Undefined name user

I have 3 screens, login, homepage and chat. In chat I want to use user, but for some reasons I am getting an error.

Error in HomePage class while trying to pass user to the Chat: 'Undefined name 'user''.

Here samples of code:

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  String email;
  String password;

  final FirebaseAuth _auth = FirebaseAuth.instance;

  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  
  Future<String> login(String _email, String _password) async {
    FirebaseUser user = (await _firebaseAuth.signInWithEmailAndPassword(
            email: _email, password: _password))
        .user;
    () =>
        Navigator.push(context, MaterialPageRoute(builder: (context) => Bar(user: user)));
  }
 ...

Why is it not defined? I want to pass user from Login(), through Homepage() to the Chat(). Thank you in advance

EDIT: I noticed it is not defined only in List, but besides it works properly. How can I pass it to the list?

class HomePage extends StatefulWidget {
  final FirebaseUser user;

  const HomePage({Key key, this.user}) : super(key:key);

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


class _BarState extends State<HomePage> {

  void test() {
    () =>
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => 
Chat(user: widget.user))); < ---- WORKING
  }

  int tabIndex = 0;
  List<Widget> widgetOptions = [
    Match(),
    Chat(user: widget.user), < --- NOT WORKING
    AddBook(),
    Profile(),
  ];

Upvotes: 0

Views: 785

Answers (3)

Ranjeet
Ranjeet

Reputation: 579

Here you want to access user object in other screen, instead of passing it in cconstructor, create a singleton class, Like this

class AuthUser {
  static var authUserId;
  static var email;
  static var userName;
  static var role;
  static var companyId;
} 

During login Set values like this, please check here print(user); and set value respectively

Future<String> login(String _email, String _password) async {
    FirebaseUser user = (await _firebaseAuth.signInWithEmailAndPassword(
            email: _email, password: _password))
        .user;
    () =>
AuthUser.email = user.email,
AuthUser.email = user.userName,
..........
       ));
  }

Access data in other screens like, AuthUser.email, AuthUser.userName.....

Upvotes: 1

Argel Bejarano
Argel Bejarano

Reputation: 622

when you are using a stateful widgets and what to get properties from constructor you need to do it like this:

widget.varNameInConstructor

most of the time it's not needed but if you want to assign that to you own new variable in state you can do it at initState.

Upvotes: 0

endrew rafael
endrew rafael

Reputation: 28

Use Chat(user: widget.user) instead.

Upvotes: 0

Related Questions