login.dart 9.68 KB
Newer Older
1
2

import 'package:flutter/cupertino.dart';
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:my_kart_flash_app/screens/homepage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:fluttertoast/fluttertoast.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {

  final GoogleSignIn googleSignIn = new GoogleSignIn();
  final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
  final FirebaseAuth _auth = FirebaseAuth.instance;
  FirebaseAuth auth = FirebaseAuth.instance;
22
23
24
25

  final _formKey = GlobalKey<FormState>();
  TextEditingController _emailTextController = TextEditingController();
  TextEditingController _passwordTextController = TextEditingController();
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
  SharedPreferences preferences;
  bool loading = false;
  bool isLoggedin = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isSignedIn();
  }
  void isSignedIn() async{
    setState(() {
      loading = true;
    });

    preferences = await SharedPreferences.getInstance();
    isLoggedin = await googleSignIn.isSignedIn();

    if(isLoggedin){
      Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomePage()));
    }

    setState(() {
      loading = false;
    });
  }

  Future handleSignIn() async{
    preferences = await SharedPreferences.getInstance();

    setState(() {
      loading = true;
    });

    GoogleSignInAccount googleUser = await googleSignIn.signIn();
    GoogleSignInAuthentication googleSignInAuthentication = await googleUser.authentication;
    /*FirebaseUser firebaseUser = await firebaseAuth.signInWithGoogle(
      idToken: googleSignInAuthentication.idToken,
      accessToken: googleSignInAuthentication.accessToken);*/

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleSignInAuthentication.accessToken,
      idToken: googleSignInAuthentication.idToken,
    );
    final FirebaseUser firebaseUser = (await _auth.signInWithCredential(credential)).user;
    
    if(firebaseUser != null){
      final QuerySnapshot result = await Firestore.instance.collection("users").where("id",isEqualTo: firebaseUser.uid).getDocuments();
      final List<DocumentSnapshot> documents =result.documents;

      if(documents.length == 0){
        // Insert the new user to our collection if the user is not found
        Firestore.instance.collection("users").document(firebaseUser.uid).setData({
          "id":firebaseUser.uid,
          "username":firebaseUser.displayName,
          "profilePicture":firebaseUser.photoUrl
        });
        await preferences.setString("id",firebaseUser.uid);
        await preferences.setString("username",firebaseUser.displayName);
        await preferences.setString("photoUrl",firebaseUser.photoUrl);
       // Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomePage()));

      }else{
        await preferences.setString("id",documents[0]['id']);
        await preferences.setString("username", documents[0]['username']);
        await preferences.setString("photoUrl",documents[0]['photoUrl']);
      }
      Fluttertoast.showToast(msg: "Log In Success");
      setState(() {
        loading = false;

      });

    }else{
    }

  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new Stack(
        children: <Widget>[
111
112
113
114
115
116
117
118
119
120
          Image.asset(
            'images/login_background/redDress.jpg',
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ),
          Container(
            color: Colors.white.withOpacity(0.2),
            width: double.infinity,
            height: double.infinity,
121
          ),
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
          Padding(
            padding: const EdgeInsets.only(top:200.0),
            child: Center(
              child: Form(
                  key: _formKey,
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(20.0),
                          color: Colors.white.withOpacity(0.5),
                          elevation:0.0,
                          child: Padding(
                            padding: const EdgeInsets.only(left:12.0),
                            child: TextFormField(
                              controller: _emailTextController,
                              decoration: InputDecoration(
                                hintText: "Email",
                                icon: Icon(Icons.email)
                            ),
                              validator: (value){
                                if(value.isEmpty){
                                  Pattern pattern =
                                      r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
                                  RegExp regex = new RegExp(pattern);
                                  if(!regex.hasMatch(value))
                                    return 'Please make sure your email address is valid';
                                  else
                                    return null;
                                }
                              },
                          ),
                        ),
                      ),
                      ),
                      Padding(
                        // padding: const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
                        padding: const EdgeInsets.all(8.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(20.0),
                          color: Colors.white.withOpacity(0.5),
                          elevation:0.0, 
                          child: Padding(
                            padding: const EdgeInsets.only(left: 12.0),
                            child: TextFormField(
                              controller: _passwordTextController,
                              decoration: InputDecoration(
                                border: InputBorder.none,
                                hintText: "Password",
                                icon: Icon(Icons.lock_outline),
                              ),
                              validator: (value) {
                                if (value.isEmpty) {
                                  return "The password field cannot be empty";
                                } else if (value.length < 6) {
                                  return "the password has to be at least 6 characters long";
                                }
                                return null;
                              },
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(20.0),
                          color: Colors.blueAccent,
                          elevation: 0.0,
                          child: MaterialButton(onPressed: (){},
                            minWidth: MediaQuery.of(context).size.width,
                               child: Text("Login",textAlign: TextAlign.center,
                               style: TextStyle(color:Colors.white,fontWeight: FontWeight.bold),
                               ),
                          ),
                        ),
                      ),
                      Expanded(child: Container(),),
                      Divider(color:Colors.white),
                      Text("Other Login Options",style: TextStyle(color:Colors.white,fontWeight: FontWeight.bold)),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(20.0),
                          color: Colors.red,
                          elevation: 0.0,
                          child: MaterialButton(onPressed: (){
                            handleSignIn();
                          },
                            minWidth: MediaQuery.of(context).size.width,
                            child: Text("Sign In with Google",textAlign: TextAlign.center,
                              style: TextStyle(color:Colors.white,fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                      ),


                    ],
                  )
              ),
            ),
          ),


228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
          Visibility(
            visible: loading ?? true,
            child: Center(
              child: Container(
                alignment: Alignment.center,
                color: Colors.white.withOpacity(0.7),
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
                ),
              ),
            ),
          )

        ],
      ),
243
244
245
246
247
248
249
250
251
252
      /*bottomNavigationBar: Container(
        child : Padding(
          padding: const EdgeInsets.only(left:12.0, right:12.0,top:8.0, bottom: 8.0),
          child: FlatButton(
                color: Colors.red,
                onPressed: (){
                  handleSignIn();
                },child: Text("Sign In / Sign Up with Google",style: TextStyle(color: Colors.white70),)),
        ),
        ),*/
253
254
255
256
257

    );
  }

}