Home > Net >  How do I access the variables from my provider class inside another class in flutter?
How do I access the variables from my provider class inside another class in flutter?

Time:02-19

I'm trying to call the function googleLogin from my Provider class and then insert it into my method in the List text

class Data {
  List text = [
    {
      "text": "Sign up with Google",
      "icon": const Icon(
        FontAwesomeIcons.google,
        color: Colors.red,
        size: 20,
      ),
      "method": () {
        print("the sign up button is working");
      }
    },
    {
      "text": "Sign up with Facebook",
      "icon":
          const Icon(FontAwesomeIcons.facebook, color: Colors.blue, size: 20),
      "method": () {
        print("signing up via facebook");
      }
    },
    {
      "text": "Sign up with email",
      "icon":
          const Icon(FontAwesomeIcons.envelope, color: Colors.white, size: 20),
      "method": () {
        print("signing up with email ");
      }
    },
    {
      "text": "Sign up as a Guest",
      "icon": const Icon(FontAwesomeIcons.user, color: Colors.white, size: 20),
      "method": () {
        print("signing up as guest");
      }
    }
  ];}

here's my provider code

class Auth extends ChangeNotifier
 {
  final googleSignIn = GoogleSignIn();
  GoogleSignInAccount? user;

  Future googleLogin() async {
    final googleUser = await googleSignIn.signIn();
    if (googleUser == null) return;
    user = googleUser;
    final googleAuth = await googleUser.authentication;

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

    await FirebaseAuth.instance.signInWithCredential(credentials);
  }
}

CodePudding user response:

You should then inject the BuildContext into your Data class and fetch Auth via the provider, like this:

class Data {
   Auth? auth;

   Data(BuildContext ctx) {
      auth = Provider.of<Auth>(context, listen: false);
   }

   /// then inside your List text…
   List text = [
      { 
        “method”: () async {
          await auth!.googleLogin();
        }
      }
   ];
}

Something around those lines. You could also refactor it and instead wrap you List text into a method in which you inject the Provider or even the whole service itself so you can call it from inside. My two cents.

  • Related