codekls
codekls

Reputation: 189

Importing Data from another class to Stateful Widget

I'm authenticating a user on one screen then pushing them to another screen but on the other screen the variable is not accessible which contains user details which I've passed through a variable. detailsUser is not accessible in the Home(); and even though I've mentioned to push on another page. It authenticates and doesn't take me to another screen.

class SignInScreen extends StatefulWidget {
  @override
  _SignInScreenState createState() => _SignInScreenState();
}

class _SignInScreenState extends State<SignInScreen> {

  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  Future<FirebaseUser> _signIn(BuildContext context) async{
    Fluttertoast.showToast(
        msg: 'Signed In'
    );

    final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
    final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
        idToken: googleAuth.accessToken,
        accessToken: googleAuth.idToken,
    );

    FirebaseUser userDetails = (await _firebaseAuth.signInWithCredential(credential)) as FirebaseUser;
    ProviderDetails providerInfo = new ProviderDetails(userDetails.providerId);

    List<ProviderDetails> providerData = List <ProviderDetails>();
    providerData.add(providerInfo);

    UserDetails details = UserDetails(
      userDetails.providerId,
      userDetails.displayName,
      userDetails.photoUrl,
      userDetails.email,
      providerData);

    Navigator.push(context, MaterialPageRoute(builder: (context) => ThemeConsumer(child: Home(detailsUser: details))));

    return userDetails;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold();
class Home extends StatefulWidget {
  final UserDetails detailsUser;

  Home({Key key, @required this.detailsUser}) : super(key: key);

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

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
     body: Center(
     child: Text(
     detailsUser.username //detailsUser is not accessible here, why?
)));

Upvotes: 0

Views: 147

Answers (2)

Shailendra Madda
Shailendra Madda

Reputation: 21551

As Patel Pinkal said in comments:

Use this "widget.detailsUser.username" 

instead of

"detailsUser.username"

Upvotes: 1

HII
HII

Reputation: 4129

To access the Widget fields from within the State class of that widget, you can use widget.fieldName (as Patel Pinkal commented)

here is a link to get more familiar with widgets in flutter

Upvotes: 1

Related Questions