Home > Mobile >  How to use 'context' in provider store in flutter?
How to use 'context' in provider store in flutter?

Time:06-13

I'm trying to write showDialog function in the provider store, so I can separate UI codes and business logic codes. However, I can't write the context inside showDialog and causes error that Undefined name 'context'. I'm wondering why I can't write context in provider and how can I fix this problem.

This is the provider codes and I want to put showDialog function.


class LoginSignupData extends ChangeNotifier{
  final authentication = FirebaseAuth.instance;

  bool isSignup = true;
  bool isSignupValid = false;
  final formKey = GlobalKey<FormState>();
  String userName = '';
  String userEmail = '';
  String userPassword = '';
  String nameError = 'Please enter at least 4 characters';
  String emailError = 'Please enter a valid email address.';
  String passwordError = 'Password must be at least 7 characters long.';

  changeBool(status){
    isSignup = status;
    notifyListeners();
  }

  signIn() async{
    showDialog(
        context: context, // error
        barrierDismissible: false,
        builder: (context) => const Center(child: CircularProgressIndicator(),)
    )
    try {
      await authentication.signInWithEmailAndPassword(
          email: userEmail, password: userPassword
      );
    } on FirebaseAuthException catch (e) {
      print('FirebaseAuthException : $e');
    }
    notifyListeners();
  }

  tryValidation() {
    final isValid = formKey.currentState!.validate();
    if (isValid) {
      formKey.currentState!.save();
      isSignupValid = true;
      notifyListeners();
    }
    notifyListeners();
  }
}`

CodePudding user response:

when declaring the signIn() function, make it like this.. signIn(BuildContext context).. then when you call it from another method/function make sure to pass the context of which you call it from.. like this.. signIn(context)

  • Related