Files
topicApp/lib/main.dart
2024-11-10 13:08:37 +08:00

287 lines
9.9 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:topic/HomePage.dart';
import 'package:mysql_client/mysql_client.dart';
import 'package:topic/NoSwipeBackRoute.dart';
import 'package:topic/RegisterPage.dart';
import 'package:topic/ForgetPasswordPage.dart';
import 'package:validators/validators.dart' as validator;
import 'generated/l10n.dart';
void main() {
runApp(
MaterialApp(
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
], //add
supportedLocales: S.delegate.supportedLocales, // add
home: LoginPage(),
)
);
}
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _ageController = TextEditingController();
bool _passwordNotVisible = true;
@override
void initState() {
//初始化
_setLanguage(); //設定語言
super.initState();
_fetchData(); //連資料庫
_CheckPreLoginInfo(); //確定有先前有無登入
}
void _fetchData() async {
//MYSQL
final conn = await MySQLConnection.createConnection(
host: '203.64.84.154',
// host:'10.0.2.2',
//127.0.0.1 10.0.2.2
port: 33061,
userName: 'root',
password: 'Topic@2024',
// password: '0000',
databaseName: 'care', //testdb
// databaseName: 'testdb',
);
await conn.connect();
}
void _CheckPreLoginInfo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//get user data from share preference else set empty to check not login before
String loginUserEmail = prefs.getString("email") ?? "";
//replace screen to HomePage if there are previous data in share preference
if (loginUserEmail != "") {
Navigator.pushReplacement(
context,
NoSwipeBackRoute(
builder: (context) => HomePage(
email: loginUserEmail,
),
),
);
}
}
void _setLanguage() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String preLanguage = prefs.getString("language") ?? "";
Locale locale = preLanguage == "" ? Localizations.localeOf(context) : Locale(preLanguage);
S.load(locale);
setState(() {});
}
void _setLoginInfo(String email) async {
//save user email into share preference to let app can auto login next open
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("email", email);
}
void loginBtn() async {
final conn = await MySQLConnection.createConnection(
host: '203.64.84.154',
port: 33061,
userName: 'root',
password: 'Topic@2024',
databaseName: 'care',
);
await conn.connect();
try {
// 獲取用戶輸入的帳號和密碼
String email = _emailController.text;
String password = _ageController.text;
print('输入的信箱: $email');
print('输入的密碼: $password');
// 查詢數據庫,检查是否有匹配的帳號
IResultSet result;
if (validator.isEmail(email)) {
result = await conn.execute(
'SELECT * FROM HomeLogin WHERE homeEmail = :email AND homePassword = :password',
{'email': email, 'password': password},
);
}
else{
result = await conn.execute(
'SELECT * FROM HomeLogin WHERE homeUserName = :email AND homePassword = :password',
{'email': email, 'password': password},
);
email = result.rows.first.colByName("homeEmail").toString();
}
print('查詢結果行數: ${result.rows.length}');
if (result.rows.isNotEmpty) {
_emailController.clear();
_ageController.clear();
// 如果找到匹配的帳號,登入成功,跳轉到主頁
_setLoginInfo(email);
Navigator.pushReplacement(
context,
NoSwipeBackRoute(
builder: (context) => HomePage(
email: email,
),
),
);
} else {
// 没有找到匹配的帳號,提示登入失敗
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('登入失敗:帳號或密碼錯誤')),
);
}
} catch (e) {
print('資料庫錯誤: $e');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('登入失敗:系統錯誤')),
);
} finally {
await conn.close();
}
}
@override
Widget build(BuildContext context) {
debugPaintSizeEnabled = false;
//by use PopScope and disable can Pop avoid android user pop back by back button
return PopScope(
canPop: false,
child: Scaffold(
body: SafeArea(
child: Center(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
margin: EdgeInsets.only(bottom: 40), // 添加間距
height: 100, // 設置logo高度
child: Icon(
Icons.account_circle,
size: 100, // 設置圖標大小
color: Color(0xFF4FC3F7), // 設置圖標颜色
),
),
Text(
'全方位照護守護者',
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.bold,
color: Colors.black,
),
), //全方位照護守護者
SizedBox(height: 20),
TextField(
controller: _emailController, // 绑定電子信箱输入框的控制器
decoration: InputDecoration(
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.email_outlined),
//https://www.fluttericon.cn/v
labelText: S.of(context).email_label,
),
), //電子信箱
SizedBox(height: 20),
TextField(
controller: _ageController,
decoration: InputDecoration(
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock_outlined),
suffixIcon: IconButton(
icon: Icon(_passwordNotVisible
? Icons.visibility
: Icons.visibility_off),
onPressed: () {
setState(
() {
_passwordNotVisible = !_passwordNotVisible;
},
);
},
),
labelText: S.of(context).password_label,
),
obscureText: _passwordNotVisible,
), //密碼
SizedBox(height: 20),
ElevatedButton(
onPressed: loginBtn,
/*() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
},*/
child: Text(S.of(context).login_button),
style: ElevatedButton.styleFrom(
backgroundColor: Color(0xFF4FC3F7),
padding:
EdgeInsets.symmetric(horizontal: 50, vertical: 15),
textStyle: TextStyle(fontSize: 18),
),
), //登入
SizedBox(height: 10),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RegisterPage()),
);
},
child: Text(S.of(context).register_button),
style: TextButton.styleFrom(
// TODO: In physical devices, the background color of the button is transparent
backgroundColor: Colors.transparent, // 無背景颜色
textStyle: TextStyle(fontSize: 18),
shadowColor: Colors.transparent, // 去除陰影
),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ForgetPasswordPage()),
);
},
child: Text(S.of(context).forgot_password),
style: TextButton.styleFrom(
backgroundColor: Colors.transparent, // 無背景颜色
textStyle: TextStyle(fontSize: 18),
shadowColor: Colors.transparent, // 去除陰影
),
),
],
),
),
),
),
),
),
);
}
}