Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:io';
- import 'package:firebase_auth/firebase_auth.dart' as fAuth;
- import 'package:flutter/gestures.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
- import 'package:flutter_svg/svg.dart';
- import 'package:google_fonts/google_fonts.dart';
- import 'package:investorv2/generated/assets.dart';
- import 'package:investorv2/singleton/shared_pref.dart';
- import 'package:investorv2/utility/apple_signin.dart';
- import 'package:investorv2/utility/baseFunctions.dart';
- import 'package:investorv2/utility/colors.dart';
- import 'package:investorv2/utility/customStrings.dart';
- import 'package:investorv2/utility/google_signin.dart';
- import 'package:investorv2/utility/routes.dart';
- import 'package:investorv2/utility/valueStrings.dart';
- import 'package:investorv2/view/common/progressBar.dart';
- import 'package:local_auth/local_auth.dart';
- import 'package:provider/provider.dart';
- import '../../provider/auth_provider.dart';
- import '../../singleton/logger.dart';
- class LoginPage extends StatefulWidget {
- const LoginPage({super.key});
- @override
- LoginPageState createState() => LoginPageState();
- }
- class LoginPageState extends State<LoginPage> {
- final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
- final emailController = TextEditingController();
- final passwordController = TextEditingController();
- bool passwordVisible = true;
- late AuthProvider provider;
- bool isAppleSignInAvailable = false;
- final LocalAuthentication auth = LocalAuthentication();
- _SupportState _supportState = _SupportState.unknown;
- bool _canCheckBiometrics = false;
- List<BiometricType>? _availableBiometrics;
- String _authorized = 'Not Authorized';
- bool _isAuthenticating = false;
- @override
- void initState() {
- provider = Provider.of<AuthProvider>(context, listen: false);
- if (Platform.isIOS) {
- appleSigninAvailability();
- }
- super.initState();
- auth.isDeviceSupported().then(
- (bool isSupported) => setState(() {
- _supportState =
- isSupported ? _SupportState.supported : _SupportState.unsupported;
- }),
- );
- }
- @override
- Widget build(BuildContext context) {
- return SafeArea(
- child: Center(
- child: SingleChildScrollView(
- physics: ScrollPhysics(),
- child: Padding(
- padding: const EdgeInsets.all(20.0),
- child: Column(
- children: <Widget>[
- SizedBox(
- child: SvgPicture.asset(
- "assets/images/ic_ifarmer.svg",
- height: 40,
- width: 100,
- ),
- ),
- SizedBox(height: 30),
- Form(
- key: _formKey,
- child: Column(
- children: <Widget>[
- Align(
- alignment: AlignmentDirectional.centerStart,
- child: Text(
- CustomStrings.email,
- style: GoogleFonts.poppins(
- fontSize: 14,
- fontWeight: FontWeight.w400,
- color: ProjectColors.black4,
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- softWrap: true,
- textAlign: TextAlign.start,
- ),
- ),
- SizedBox(height: 10),
- TextFormField(
- style: GoogleFonts.poppins(
- color: ProjectColors.black4,
- fontSize: 14,
- fontWeight: FontWeight.w500,
- ),
- maxLines: 1,
- controller: emailController,
- validator: (value) {
- if (value == null || value.isEmpty) {
- return CustomStrings.required;
- } else if (!RegExp(
- r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
- ).hasMatch(value)) {
- return CustomStrings.invalidEmail;
- }
- return null; // Valid input
- },
- keyboardType: TextInputType.emailAddress,
- decoration: InputDecoration(
- fillColor: ProjectColors.gray,
- filled: true,
- hintStyle: GoogleFonts.poppins(
- color: ProjectColors.black4.withValues(alpha: 90),
- fontSize: 14,
- fontWeight: FontWeight.w500,
- ),
- errorBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(10.0),
- borderSide: BorderSide(
- color: Colors.red.shade800,
- width: 0.5,
- ),
- ),
- focusedBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(10.0),
- borderSide: BorderSide(
- color: ProjectColors.primaryColor,
- ),
- ),
- focusedErrorBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(10.0),
- borderSide: BorderSide(
- color: Colors.red.shade800,
- width: 0.5,
- ),
- ),
- contentPadding: EdgeInsets.fromLTRB(
- 20.0,
- 15.0,
- 20.0,
- 15.0,
- ),
- hintText: CustomStrings.emailHint,
- border: OutlineInputBorder(
- borderSide: BorderSide.none,
- borderRadius: BorderRadius.circular(10.0),
- ),
- ),
- ),
- SizedBox(height: 20.0),
- Align(
- alignment: AlignmentDirectional.centerStart,
- child: Text(
- CustomStrings.pin,
- style: GoogleFonts.poppins(
- fontSize: 14,
- fontWeight: FontWeight.w400,
- color: ProjectColors.black4,
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- softWrap: true,
- textAlign: TextAlign.start,
- ),
- ),
- SizedBox(height: 10),
- TextFormField(
- style: GoogleFonts.poppins(
- color: ProjectColors.black4,
- fontSize: 14,
- fontWeight: FontWeight.w500,
- ),
- maxLines: 1,
- controller: passwordController,
- inputFormatters: [
- FilteringTextInputFormatter.digitsOnly,
- ],
- validator: (value) {
- if (value!.trim().isEmpty) {
- return CustomStrings.required;
- }
- if (value.trim().length < 6) {
- return CustomStrings.min6;
- }
- return null;
- },
- obscureText: passwordVisible,
- keyboardType: TextInputType.number,
- decoration: InputDecoration(
- fillColor: ProjectColors.gray,
- filled: true,
- hintStyle: GoogleFonts.poppins(
- color: ProjectColors.black4.withValues(alpha: 90),
- fontSize: 14,
- fontWeight: FontWeight.w500,
- ),
- errorBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(10.0),
- borderSide: BorderSide(
- color: Colors.red.shade800,
- width: 0.5,
- ),
- ),
- focusedBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(10.0),
- borderSide: BorderSide(
- color: ProjectColors.primaryColor,
- ),
- ),
- focusedErrorBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(10.0),
- borderSide: BorderSide(
- color: Colors.red.shade800,
- width: 0.5,
- ),
- ),
- contentPadding: EdgeInsets.fromLTRB(
- 20.0,
- 15.0,
- 20.0,
- 15.0,
- ),
- hintText: CustomStrings.pinHint,
- border: OutlineInputBorder(
- borderSide: BorderSide.none,
- borderRadius: BorderRadius.circular(10.0),
- ),
- suffixIcon: IconButton(
- icon: Icon(
- passwordVisible
- ? Icons.visibility
- : Icons.visibility_off,
- color: ProjectColors.black4,
- ),
- onPressed: () {
- setState(() {
- passwordVisible = !passwordVisible;
- });
- },
- ),
- ),
- ),
- ],
- ),
- ),
- Align(
- alignment: AlignmentDirectional.centerStart,
- child: TextButton(
- onPressed: () {
- Navigator.pushNamed(context, forgetPasswordPage);
- },
- child: Text(
- CustomStrings.forgotPassword,
- style: GoogleFonts.poppins(
- fontSize: 12,
- fontWeight: FontWeight.w400,
- color: ProjectColors.primaryColor,
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- softWrap: true,
- textAlign: TextAlign.start,
- ),
- ),
- ),
- Row(
- mainAxisAlignment: MainAxisAlignment.start,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Expanded(
- child: ElevatedButton(
- style: ButtonStyle(
- backgroundColor: WidgetStateProperty.all(
- ProjectColors.primaryColor,
- ),
- padding: WidgetStateProperty.all(
- EdgeInsets.fromLTRB(8, 16, 8, 16),
- ),
- shape: WidgetStatePropertyAll(
- RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(10),
- ),
- ),
- ),
- onPressed: () {
- if (_formKey.currentState!.validate()) {
- provider
- .loginCall(
- email: emailController.text.trim(),
- password: passwordController.text,
- )
- .then((statusCode) {
- if (statusCode == 200) {
- SharedPref.setModel(
- loginModel,
- context
- .read<AuthProvider>()
- .logInResponse,
- );
- SharedPref.setString(
- token,
- context
- .read<AuthProvider>()
- .logInResponse
- .authToken!,
- );
- if (!context
- .read<AuthProvider>()
- .logInResponse
- .privacyFlag!) {
- Navigator.pushReplacementNamed(
- context,
- privacyPolicyPage,
- arguments: false,
- );
- } else {
- Navigator.pushReplacementNamed(
- context,
- loggedHomePage,
- );
- }
- }
- });
- }
- },
- child: Row(
- mainAxisAlignment: MainAxisAlignment.center,
- spacing: 6,
- children: [
- SvgPicture.asset(
- "assets/images/ic_login.svg",
- height: 24,
- width: 24,
- colorFilter: ColorFilter.mode(
- ProjectColors.white,
- BlendMode.srcIn,
- ),
- ),
- Text(
- CustomStrings.login,
- style: GoogleFonts.poppins(
- fontWeight: FontWeight.w500,
- fontSize: 16,
- color: ProjectColors.white,
- ),
- ),
- ],
- ),
- ),
- ),
- Visibility(
- visible: _supportState == _SupportState.supported,
- child: IconButton(
- onPressed: () {
- _checkBiometrics().then((value) {
- if (_canCheckBiometrics) {
- _getAvailableBiometrics().then((value) {
- _authenticateWithBiometrics().then((value) {
- Log().showMessageToast(message: _authorized);
- });
- });
- }
- });
- },
- icon: Image(
- image: AssetImage(Assets.imagesIcBiometric),
- width: 60,
- height: 60,
- ),
- ),
- ),
- ],
- ),
- SizedBox(height: 10),
- SizedBox(
- height: 1,
- child: Container(
- color: ProjectColors.black6,
- padding: EdgeInsets.only(top: 10, bottom: 10),
- ),
- ),
- SizedBox(height: 10),
- Align(
- alignment: AlignmentDirectional.centerStart,
- child: RichText(
- textAlign: TextAlign.start,
- text: TextSpan(
- style: GoogleFonts.poppins(
- fontSize: 12.0,
- color: ProjectColors.black4,
- fontWeight: FontWeight.w400,
- ),
- children: <TextSpan>[
- TextSpan(
- text: CustomStrings.doNotAccount,
- style: GoogleFonts.poppins(
- fontSize: 12.0,
- color: ProjectColors.black4,
- fontWeight: FontWeight.w400,
- ),
- ),
- TextSpan(
- text: CustomStrings.signUp,
- recognizer:
- TapGestureRecognizer()
- ..onTap = () {
- Navigator.pushNamed(
- context,
- registrationPage,
- );
- },
- style: GoogleFonts.poppins(
- fontSize: 12.0,
- color: ProjectColors.primaryColor,
- fontWeight: FontWeight.w400,
- ),
- ),
- ],
- ),
- ),
- ),
- Container(
- margin: EdgeInsets.only(top: 20.0),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- mainAxisSize: MainAxisSize.max,
- children: <Widget>[
- Card(
- margin: EdgeInsets.all(0.0),
- elevation: 2,
- shape: RoundedRectangleBorder(
- side: BorderSide(
- color: ProjectColors.primaryColor,
- width: 0.5,
- ),
- borderRadius: BorderRadius.circular(4.0),
- ),
- child: GestureDetector(
- onTap: () async {
- goggleSignIn();
- },
- child: Container(
- color: ProjectColors.white,
- padding: EdgeInsets.symmetric(vertical: 10.0),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: <Widget>[
- SvgPicture.asset(
- "assets/images/google.svg",
- height: 25.0,
- width: 18.0,
- ),
- SizedBox(width: 10),
- Text(
- CustomStrings.google,
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.w500,
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- SizedBox(height: 15),
- Visibility(
- visible: isAppleSignInAvailable,
- child: Card(
- margin: EdgeInsets.all(0.0),
- elevation: 2,
- color: Colors.black,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(4.0),
- ),
- child: GestureDetector(
- onTap: () {
- appleSignIn();
- },
- child: Container(
- padding: EdgeInsets.symmetric(
- vertical: 10.0,
- horizontal: 10.0,
- ),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: <Widget>[
- SvgPicture.asset(
- "assets/images/apple_logo.svg",
- height: 25.0,
- width: 18.0,
- ),
- SizedBox(width: 10),
- Text(
- CustomStrings.apple,
- style: TextStyle(
- fontSize: 14,
- color: Colors.white,
- fontWeight: FontWeight.w500,
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- SizedBox(height: 10),
- ],
- ),
- ),
- ),
- ),
- );
- }
- appleSigninAvailability() async {
- var value = await AppleAuthService.isAppleSignInAvailable();
- setState(() {
- isAppleSignInAvailable = value;
- });
- }
- appleSignIn() async {
- fAuth.UserCredential? userCredential;
- userCredential = await AppleAuthService().signInWithApple();
- String name = SharedPref.getString("appleDisplayName");
- Log().printInfo("Saved Name:$name");
- if (userCredential != null) {
- CustomProgressDialog.show(message: "Signing In...", isDismissible: false);
- fAuth.User? user = userCredential.user;
- Map<String, dynamic> map = {};
- if (user != null) {
- map["uid"] = user.uid;
- map['provider'] = "apple";
- if (user.email != null) {
- map['email'] = user.email;
- BaseFunctions().setEmail(user.email!);
- }
- map['name'] = name;
- if (user.photoURL != null) {
- map['image'] = user.photoURL ?? "";
- }
- provider.socialLogin(map: map).then((statusCode) {
- Log().printInfo(statusCode.toString());
- if (statusCode == 200) {
- if (statusCode == 200) {
- SharedPref.setModel(
- loginModel,
- context.read<AuthProvider>().logInResponse,
- );
- SharedPref.setString(
- token,
- context.read<AuthProvider>().logInResponse.authToken!,
- );
- if (!context.read<AuthProvider>().logInResponse.privacyFlag!) {
- Navigator.pushReplacementNamed(
- context,
- privacyPolicyPage,
- arguments: false,
- );
- } else {
- Navigator.pushReplacementNamed(context, loggedHomePage);
- }
- }
- }
- });
- } else {
- CustomProgressDialog.hide();
- }
- } else {
- CustomProgressDialog.hide();
- }
- }
- goggleSignIn() async {
- fAuth.UserCredential? userCredential;
- userCredential = await GoogleAuthService().signInWithGoogle();
- // Access user details
- if (userCredential != null) {
- CustomProgressDialog.show(message: "Signing In...", isDismissible: false);
- fAuth.User? user = userCredential.user;
- if (user != null) {
- Log().printInfo("User UID: ${user.uid}");
- Log().printInfo("User Display Name: ${user.displayName}");
- Log().printInfo("User Email: ${user.email}");
- Log().printInfo("User Photo URL: ${user.photoURL}");
- Map<String, dynamic> map = {};
- map['uid'] = user.uid;
- map['provider'] = "google";
- if (user.email != null) {
- map['email'] = user.email ?? "";
- BaseFunctions().setEmail(user.email ?? "");
- }
- if (user.displayName != null) {
- map['name'] = user.displayName ?? "";
- BaseFunctions().setEmail(user.displayName ?? "");
- }
- map['image'] = user.photoURL ?? "";
- provider.socialLogin(map: map).then((statusCode) {
- Log().printInfo(statusCode.toString());
- if (statusCode == 200) {
- if (statusCode == 200) {
- SharedPref.setModel(
- loginModel,
- context.read<AuthProvider>().logInResponse,
- );
- SharedPref.setString(
- token,
- context.read<AuthProvider>().logInResponse.authToken!,
- );
- if (!context.read<AuthProvider>().logInResponse.privacyFlag!) {
- Navigator.pushReplacementNamed(
- context,
- privacyPolicyPage,
- arguments: false,
- );
- } else {
- Navigator.pushReplacementNamed(context, loggedHomePage);
- }
- }
- }
- });
- } else {
- CustomProgressDialog.hide();
- }
- } else {
- CustomProgressDialog.hide();
- }
- }
- Future<void> _checkBiometrics() async {
- late bool canCheckBiometrics;
- try {
- canCheckBiometrics = await auth.canCheckBiometrics;
- } on PlatformException catch (e) {
- canCheckBiometrics = false;
- print(e);
- }
- if (!mounted) {
- return;
- }
- setState(() {
- _canCheckBiometrics = canCheckBiometrics;
- });
- }
- Future<void> _getAvailableBiometrics() async {
- late List<BiometricType> availableBiometrics;
- try {
- availableBiometrics = await auth.getAvailableBiometrics();
- } on PlatformException catch (e) {
- availableBiometrics = <BiometricType>[];
- print(e);
- }
- if (!mounted) {
- return;
- }
- setState(() {
- _availableBiometrics = availableBiometrics;
- });
- }
- Future<void> _authenticate() async {
- bool authenticated = false;
- try {
- setState(() {
- _isAuthenticating = true;
- _authorized = 'Authenticating';
- });
- authenticated = await auth.authenticate(
- localizedReason: 'Let OS determine authentication method',
- options: const AuthenticationOptions(stickyAuth: true),
- );
- setState(() {
- _isAuthenticating = false;
- });
- } on PlatformException catch (e) {
- setState(() {
- _isAuthenticating = false;
- _authorized = 'Error - ${e.message}';
- });
- return;
- }
- if (!mounted) {
- return;
- }
- setState(
- () => _authorized = authenticated ? 'Authorized' : 'Not Authorized',
- );
- }
- Future<void> _authenticateWithBiometrics() async {
- bool authenticated = false;
- try {
- setState(() {
- _isAuthenticating = true;
- _authorized = 'Authenticating';
- });
- authenticated = await auth.authenticate(
- localizedReason:
- 'Scan your fingerprint (or face or whatever) to authenticate',
- options: const AuthenticationOptions(
- stickyAuth: true,
- biometricOnly: true,
- ),
- );
- setState(() {
- _isAuthenticating = false;
- _authorized = 'Authenticating';
- });
- } on PlatformException catch (e) {
- setState(() {
- _isAuthenticating = false;
- _authorized = 'Error - ${e.message}';
- });
- return;
- }
- if (!mounted) {
- return;
- }
- final String message = authenticated ? 'Authorized' : 'Not Authorized';
- setState(() {
- _authorized = message;
- });
- }
- Future<void> _cancelAuthentication() async {
- await auth.stopAuthentication();
- setState(() => _isAuthenticating = false);
- }
- }
- enum _SupportState { unknown, supported, unsupported }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement