瀏覽代碼

functionality to not show login screen, if alr logged in

juan 1 周之前
父節點
當前提交
54585b163d
共有 2 個文件被更改,包括 152 次插入95 次删除
  1. 148 94
      lib/login.dart
  2. 4 1
      lib/main.dart

+ 148 - 94
lib/login.dart

@@ -1,6 +1,9 @@
 import 'dart:convert';
 import 'package:flutter/material.dart';
 import 'package:http/http.dart' as http;
+import 'package:shared_preferences/shared_preferences.dart';
+import 'dart:io';
+import 'package:path_provider/path_provider.dart';
 
 class AuthService {
   Future<bool> isUserLoggedIn() async {
@@ -10,15 +13,21 @@ class AuthService {
       print(response.body);
       if (response.statusCode == 200) {
         print('all good in the east!');
-        List json = jsonDecode(response.body);
-        print(json[0]);
-        return true;
+        String jsonOuter = jsonDecode(response.body);
+        Map<String, dynamic> json = jsonDecode(jsonOuter);
+        // print(json["is_logged_in"]);
+        return json["is_logged_in"];
       }
     } catch (e) {
       print(e);
     }
     return false;
   }
+
+  Future<bool> loginUser(String email, String password) async {
+    try {} catch (e) {}
+    return false;
+  }
 }
 
 class LoginPage extends StatefulWidget {
@@ -28,6 +37,43 @@ class LoginPage extends StatefulWidget {
   _LoginPageState createState() => _LoginPageState();
 }
 
+class SplashScreen extends StatefulWidget {
+  @override
+  _SplashScreenState createState() => _SplashScreenState();
+}
+
+class _SplashScreenState extends State<SplashScreen> {
+  final AuthService _authService = AuthService();
+  @override
+  void initState() {
+    super.initState();
+    _checkLoginStatus();
+  }
+
+  Future<void> _checkLoginStatus() async {
+    // SharedPreferences prefs = await SharedPreferences.getInstance();
+    // print(prefs);
+    // bool isLoggedIn = prefs.getBool('isLoggedIn') ?? false;
+    bool isLoggedIn = await _authService.isUserLoggedIn();
+    print("is loogeed in $isLoggedIn");
+    if (isLoggedIn) {
+      print('here');
+      Navigator.pushReplacementNamed(context, '/home');
+    } else {
+      Navigator.pushReplacementNamed(context, '/login');
+    }
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Center(
+      child: Scaffold(
+        body: Center(child: CircularProgressIndicator()),
+      ),
+    );
+  }
+}
+
 class _LoginPageState extends State<LoginPage> {
   final AuthService _authService = AuthService();
   // Controllers for capturing user input
@@ -37,20 +83,19 @@ class _LoginPageState extends State<LoginPage> {
   // Key to identify the form
   final _formKey = GlobalKey<FormState>();
 
-  void checkLogin() async {
-    // try {
-    //   var url = Uri.http('127.0.0.1:3001', 'is_logged_in');
-    //   var response = await http.get(url);
-    //   print(response.body);
-    //   if (response.statusCode == 200) {
-    //     print('all good on the west');
-    //   }
-    // } catch (e) {
-    //   print(e);
-    // }
-    bool isLoggedIn = await _authService.isUserLoggedIn();
-    
-  }
+  // void checkLogin() async {
+  //   try {
+  //     var url = Uri.http('127.0.0.1:3001', 'is_logged_in');
+  //     var response = await http.get(url);
+  //     print(response.body);
+  //     if (response.statusCode == 200) {
+  //       print('all good on the west');
+  //     }
+  //   } catch (e) {
+  //     print(e);
+  //   }
+  //   // bool isLoggedIn = await _authService.isUserLoggedIn();
+  // }
 
   // Function to handle login action
   void _handleLogin() {
@@ -71,86 +116,95 @@ class _LoginPageState extends State<LoginPage> {
 
   @override
   Widget build(BuildContext context) {
-    return Scaffold(
-      appBar: AppBar(
-        title: const Text('Login Page'),
-      ),
-      body: Padding(
-        padding: const EdgeInsets.all(16.0),
-        child: Form(
-          key: _formKey,
-          child: Align(
-            alignment: Alignment.centerLeft,
-            child: Column(
-              mainAxisSize: MainAxisSize.min,
-              crossAxisAlignment: CrossAxisAlignment.start,
-              children: [
-                Text('Sign in to your email'),
-                SizedBox(
-                  height: 5,
-                ),
-                // Email Field
-                Container(
-                  width: 200,
-                  child: TextFormField(
-                    controller: _emailController,
-                    decoration: const InputDecoration(
-                      labelText: 'Email',
-                      hintText: 'Enter your email',
-                      helperMaxLines: 1,
+    return Center(
+      child: Scaffold(
+        appBar: AppBar(
+          title: const Text('Login Page'),
+        ),
+        body: Center(
+          child: SingleChildScrollView(
+            padding: const EdgeInsets.all(16.0),
+            child: Form(
+              key: _formKey,
+              child: Align(
+                alignment: Alignment.center,
+                child: Column(
+                  mainAxisSize: MainAxisSize.min,
+                  crossAxisAlignment: CrossAxisAlignment.start,
+                  children: [
+                    Text('Sign in to your email'),
+                    SizedBox(
+                      height: 5,
                     ),
-                    validator: (value) {
-                      // Simple email validation
-                      if (value == null || value.isEmpty) {
-                        return 'Please enter your email';
-                      }
-                      if (!RegExp(r'^\S+@\S+\.\S+$').hasMatch(value)) {
-                        return 'Please enter a valid email address';
-                      }
-                      return null;
-                    },
-                  ),
-                ),
-                const SizedBox(height: 16.0),
-                // Password Field
-                Container(
-                  width: 200,
-                  child: TextFormField(
-                    controller: _passwordController,
-                    decoration: const InputDecoration(
-                      labelText: 'Password',
-                      hintText: 'Enter your password',
+                    // Email Field
+                    Container(
+                      width: 200,
+                      child: TextFormField(
+                        controller: _emailController,
+                        decoration: const InputDecoration(
+                          labelText: 'Email',
+                          hintText: 'Enter your email',
+                          helperMaxLines: 1,
+                        ),
+                        validator: (value) {
+                          // Simple email validation
+                          if (value == null || value.isEmpty) {
+                            return 'Please enter your email';
+                          }
+                          if (!RegExp(r'^\S+@\S+\.\S+$').hasMatch(value)) {
+                            // print(value);
+                            return 'Please enter a valid email address';
+                          }
+                          return null;
+                        },
+                      ),
                     ),
-                    obscureText: true, // Hide the password text
-                    validator: (value) {
-                      // Simple password validation
-                      if (value == null || value.isEmpty) {
-                        return 'Please enter your password';
-                      }
-                      if (value.length < 6) {
-                        return 'Password must be at least 6 characters long';
-                      }
-                      return null;
-                    },
-                  ),
+                    const SizedBox(height: 16.0),
+                    // Password Field
+                    Container(
+                      width: 200,
+                      child: TextFormField(
+                        controller: _passwordController,
+                        decoration: const InputDecoration(
+                          labelText: 'Password',
+                          hintText: 'Enter your password',
+                        ),
+                        obscureText: true, // Hide the password text
+                        validator: (value) {
+                          // Simple password validation
+                          if (value == null || value.isEmpty) {
+                            return 'Please enter your password';
+                          }
+                          if (value.length < 6) {
+                            return 'Password must be at least 6 characters long';
+                          }
+                          return null;
+                        },
+                      ),
+                    ),
+                    const SizedBox(height: 32.0),
+                    // Login Button
+                    SizedBox(
+                      width: 200,
+                      child: ElevatedButton(
+                        onPressed: _handleLogin,
+                        child: const Text('Login'),
+                      ),
+                    ),
+                    SizedBox(
+                      width: 200,
+                      child: ElevatedButton(
+                        // onPressed: checkLogin,
+                        onPressed: () async {
+                          await _authService.isUserLoggedIn();
+                          // print(result);
+                        },
+                        child: const Text('checker'),
+                      ),
+                    )
+                  ],
                 ),
-                const SizedBox(height: 32.0),
-                // Login Button
-                SizedBox(
-                  width: 200,
-                  child: ElevatedButton(
-                    onPressed: _handleLogin,
-                    child: const Text('Login'),
-                  ),
-                ),
-                SizedBox(
-                  width: 200,
-                  child: ElevatedButton(
-                    onPressed: checkLogin,
-                    child: const Text('checker'),
-                  ),
-                )
-              ],
+              ),
             ),
           ),
         ),

+ 4 - 1
lib/main.dart

@@ -22,10 +22,13 @@ class HyM extends StatelessWidget {
       theme: ThemeData.light(),
       title: 'HyM',
       // home: HomeScreen(),
-      home: HomeScreen(),
+      // home: HomeScreen(),
+      initialRoute: "/",
 
       routes: {
+        "/": (context) => SplashScreen(),
         "/login": (context) => const LoginPage(),
+        "/home": (context) => HomeScreen(),
         // "/email": (context) => EmailPage(),
         "/contacts": (context) => ContactsPage(),
       },