0

I am using provider as a state management in flutter. I am currently working on authentication using custom auth not firebase authentication.

I am using provider package, but when I tap on button provider give me value like Email and password does not match but when I press the button second time it give me updated value like email and password are correct.

I am writing following code:

main.dart

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [ChangeNotifierProvider(create: (_) => SignInBusinessLogic())],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Login(),
      ),
    );
  }
}

login.dart

class Login extends StatelessWidget {
  final SignInValidations _signInValidations = SignInValidations();
  final _formKey = GlobalKey<FormState>();
  TextEditingController _name = TextEditingController();
  TextEditingController _password = TextEditingController();

  @override
  Widget build(BuildContext context) {
    var _authStatus = Provider.of<SignInBusinessLogic>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("Login"),
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          children: [
            TextFormField(
              controller: _name,
              validator: (val) => _signInValidations.validateUsernameField(val)
                  ? SignInValidationsConstants.emailEmptyValidation
                  : null,
            ),
            TextFormField(
              controller: _password,
              validator: (val) => _signInValidations.validatePasswordField(val)
                  ? SignInValidationsConstants.passwordValidation
                  : null,
            ),
            _authStatus.status == Status.Authenticating
                ? CircularProgressIndicator()
                : RaisedButton(onPressed: () async {
                    if (!_formKey.currentState.validate()) {
                      return;
                    }

                    _authStatus.validateUser(
                        _name.text, _password.text, "2423");

                    switch (_authStatus.status) {
                      case Status.Initialized:
                        print("Initialize");
                        break;
                      case Status.Validated:
                        print("Validate");
                        break;
                      case Status.FirstLogin:
                        print("First Login");
                        break;
                      case Status.DeviceIDNotMatch:
                        print("Device id not match");
                        break;
                      case Status.AccessDenied:
                        print("Access Denied");
                        break;
                      default:
                        print("Default Case");
                    }
                  })
          ],
        ),
      ),
    );
  }
}

signInBusinessLogic.dart

enum Status {
  Initialized,
  FirstLogin,
  Validated,
  AccessDenied,
  DeviceIDNotMatch,
  Authenticating
}

class SignInBusinessLogic with ChangeNotifier {
  Status _status = Status.Initialized;
  AuthServices _authServices = AuthServices();

  Status get status => _status;

  StreamSubscription<List<UserModel>> validateUser(
      String email, String password, String deviceID) {
    return _authServices.validateUser(email, password, deviceID).listen((list) {
      _status = Status.Authenticating;
      notifyListeners();
      if (list.isEmpty) {
        _status = Status.AccessDenied;
        notifyListeners();
      }
      list.map((user) {
        if (user.deviceId == deviceID) {
          _status = Status.Validated;
          print(_status);
          notifyListeners();
        } else if (user.deviceId == "") {
          _status = Status.FirstLogin;
          notifyListeners();
         
        } else {
          _status = Status.DeviceIDNotMatch;
          notifyListeners();
        }
      }).toList();
    });
  }
}

AuthService Class

class AuthServices {
  final FirebaseFirestore _db = FirebaseFirestore.instance;

  ///Check if the user validates
  Stream<List<UserModel>> validateUser(
      String email, String password, String deviceID) {
    return _db
        .collection('classTeachers')
        .where('email', isEqualTo: email)
        .where('password', isEqualTo: password)
        .snapshots()
        .map((list) =>
            list.docs.map((docs) => UserModel.fromJson(docs.data())).toList());
  }
}

enter image description here

Kindly help me in solving me issue. Thanks in advance for your precious time.

Ali Coder
  • 163
  • 3
  • 14
  • First, you are using in a bad way `Provider` in your `signInBusinessLogic` class, needlessly calling `notifyListener` several times. Second, although I don't know definition of your `AuthServices` class, I doubt it to be necessary to use Streams for your case, because you need to display a state according to result of validation, so I should focus on **that result**. I recommend you to use/try [GetX](https://pub.dev/packages/get) package, or you could use FutureBuilder. Review its documentation, please. – Ουιλιαμ Αρκευα Jan 14 '21 at 15:44
  • I have added AuthService class definition and also output that i am getting from this code. – Ali Coder Jan 14 '21 at 16:28
  • I have also tested it using timer of 2 seconds after 2 seconds i am getting correct result. So how to get updated value in time using provider? Kindly help me i am new to provider – Ali Coder Jan 14 '21 at 16:40
  • Check this [post](https://stackoverflow.com/questions/53517382/query-a-single-document-from-firestore-in-flutter-cloud-firestore-plugin) and [this article](https://dev.to/kazuhideoki/how-to-get-data-from-firestore-and-show-it-on-flutterbuilder-or-streambuilder-e05). They should resolve your problem, and you will decide if you need to use `Provider`. – Ουιλιαμ Αρκευα Jan 14 '21 at 16:53
  • I am basically developing apps without using state management and quite familiar with regular programming in flutter and also done diffrnt projects but now i am moving towards provider. But getting this issue. – Ali Coder Jan 14 '21 at 17:01

0 Answers0