你好吗?
我有带护照身份验证的 laravel 后端,现在我想在 flutter 中将它与我的移动应用程序链接
我想进行身份验证,但我是 flutter 的新手,我不知道如何开始做这件事
首先我制作我的模型
这是我的第一个模型 login.dart
class Login {
final String login;
final String password;
Login (this.login,this.password);
}
我的第二个模型是 register.dart
class Register {
final String email;
final String name;
final String mobile;
final String password;
Register(
this.email,
this.name,
this.mobile,
this.password,
);
}
这是用户模型
class User {
final int id ;
final int active ;
final int confirmed ;
final String mobile ;
final String name ;
final String email ;
final String confirmation_code ;
User(this.id,this.active,this.confirmed,this.mobile,this.name,this.email,this.confirmation_code);
}
这是我的授权响应模型
import './User.dart';
class AuthResponse {
final String token;
final User user;
AuthResponse(
this.user, this.token
);
}
但现在我不知道如何进行授权并将其与这些模型链接,所以有人可以帮忙吗
谢谢
新代码
我的登录页面代码
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
import '../../common/apifunctions/requestLoginAPI.dart';
import 'package:gradient_widgets/gradient_widgets.dart';
class UserLoginPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _UserLoginPage();
}
}
class _UserLoginPage extends State<UserLoginPage> {
final TextEditingController _mobileController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
@override
void initState() {
super.initState();
_saveCurrentRoute('/UserLogin');
}
_saveCurrentRoute(String lastRoute) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.setString('LastScreenRoute', lastRoute);
}
void _gloginButton() {
Navigator.pushReplacementNamed(context, '/Home');
}
void _registerButton() {
Navigator.pushNamed(context, '/UserRegister');
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
if (Navigator.canPop(context)) {
Navigator.of(context).pushNamedAndRemoveUntil(
'/Home', (Route<dynamic> route) => false);
} else {
Navigator.of(context).pushReplacementNamed('/Home');
}
},
child: Scaffold(
body: Column(
children: <Widget>[
Image.asset('assets/img/LRUI.png'),
Form(
child: Container(
//padding: EdgeInsets.only(top: 100.0),
margin: EdgeInsets.all(35.0),
child: Center(
child: Center(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
SizedBox(
height: 99.0,
),
TextFormField(
controller: _mobileController,
decoration: InputDecoration(
labelText: 'رقم الجوال',
hintText: "رقم الجوال يجب أن يكون عشر ارقام",
),
style: TextStyle(
fontSize: 18.0,
color: Colors.grey,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 11.0),
TextFormField(
controller: _passwordController,
decoration: InputDecoration(
labelText: 'الرقم السري',
),
obscureText: true,
style: TextStyle(
fontSize: 18.0,
color: Colors.grey,
fontWeight: FontWeight.bold,
),
),
SizedBox(
height: 40.0,
),
GradientButton(
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomCenter,
colors: const <Color>[
Color(0xff4caf4e),
Color(0xff71c071),
],
),
callback: () {
SystemChannels.textInput
.invokeMethod('TextInput.hide');
requestLoginAPI(context, _mobileController.text,
_passwordController.text);
},
textStyle: TextStyle(
color: Colors.white, fontSize: 16.0),
shapeRadius: BorderRadius.circular(10.0),
child: Text(
"دخول",
),
increaseHeightBy: 20.0,
increaseWidthBy: 140.0,
),
SizedBox(
height: 35.0,
),
FlatButton(
child: Text('دخول كضيف'),
onPressed: _gloginButton,
),
FlatButton(
child: Text('تسجيل حساب جديد'),
onPressed: _registerButton,
),
],
),
),
),
),
),
),
],
),
));
}
}
这是我请求登录的Api函数代码
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../functions/ saveCurrentLogin.dart';
import '../functions/showDialog.dart';
import 'dart:convert';
import '../../Models/Login.dart';
import '../../Models/User.dart';
import '../../Models/AuthResponse.dart';
Future<Login> requestLoginAPI(BuildContext context, String login, String password) async {
final url = "http://188.166.172.146/Blooming/public/api/login";
Map<String, String> body = {
'login': login,
'password': password,
};
final response = await http.post(
url,
body: body,
);
if (response.statusCode == 200) {
final responseJson = json.decode(response.body);
var token = new AuthResponse.fromJson(responseJson);
saveCurrentLogin(responseJson);
Navigator.of(context).pushReplacementNamed('/About');
return Login.fromJson(responseJson);
} else {
final responseJson = json.decode(response.body);
saveCurrentLogin(responseJson);
showDialogSingleButton(context, "خطأ", "تأكد من معلومات الدخول", "موافق");
return null;
}
}
这是我保存当前登录功能的代码
import 'package:shared_preferences/shared_preferences.dart';
import '../../Models/AuthResponse.dart';
import '../../Models/User.dart';
saveCurrentLogin(Map responseJson) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
var token = (responseJson != null && !responseJson.isEmpty) ? AuthResponse.fromJson(responseJson).token : "";
var id = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).id : 0;
var name = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).name : "";
var email = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).email : "";
var mobile = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).mobile : "";
var active = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).active : 0;
var confirmation_code = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).confirmation_code : "";
var confirmed = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).confirmed : 0;
await preferences.setString('token', (token != null && token.length > 0) ? token : "");
await preferences.setInt('id', (id != null && id > 0) ? id : 0);
await preferences.setString('name', (name != null && name.length > 0) ? name : "");
await preferences.setString('email', (email != null && email.length > 0) ? email : "");
await preferences.setString('mobile', (mobile != null && mobile.length > 0) ? mobile : "");
await preferences.setInt('active', (active != null && active > 0) ? active : 0);
await preferences.setString('confirmation_code', (confirmation_code != null && confirmation_code.length > 0) ? confirmation_code : "");
await preferences.setInt('confirmed', (confirmed != null && confirmed > 0) ? confirmed : 0);
}
这是获取token的函数代码
import 'package:shared_preferences/shared_preferences.dart';
getToken() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
String getToken = await preferences.getString("token");
return getToken;
}
这是新的登录模型
class Login {
final String login;
final String password;
Login(this.login, this.password);
Login.fromJson(Map<String, dynamic> json)
: login = json['login'],
password = json['password'];
}
这是授权响应模型
import './User.dart';
class AuthResponse {
final String token;
User user;
AuthResponse({
this.token,
this.user,
});
factory AuthResponse.fromJson(Map<String, dynamic> parsedJson){
return AuthResponse(
token: parsedJson['token'],
user: User.fromJson(parsedJson['user'])
);
}
Map<String, dynamic> toJson() => {
'token': token,
'user':user,
};
}
这是我的用户模型
class User {
final int id;
final String name;
final String email;
final String mobile;
final int active;
final String confirmation_code;
final int confirmed;
User({
this.id,
this.name,
this.email,
this.mobile,
this.active,
this.confirmation_code,
this.confirmed,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
mobile: json['mobile'],
active: json['active'],
confirmation_code: json['confirmation_code'],
confirmed: json['confirmed'],
);
}
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'email':email,
'mobile':mobile,
'active':active,
'confirmation_code':confirmation_code,
'confirmed':confirmed,
};
}
最佳答案
最好的方法是使用 shared preferences
- 1 - 你需要安装依赖(见链接)
- 2 - 向您的服务器发出“http”请求以获取“授权 key ”
- 3 - 创建两个“共享首选项”键:
并将第一个命名为“auth_key”以存储身份验证 key 并将另一个保存为“bool”数据类型,将其命名为“is_login” 现在在 dart 的主要功能中,检查参数“is_login”,如果为真,则返回(主页,帐户...等),否则将其带到登录小部件
设置两个键的dart代码
Future<void> setUserLogin(String auth_token) async{
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString("auth_token", auth_token);
pref.setBool("is_login", true);
}
检查是否登录:
Future<bool> isUserLogin() async{
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getBool("is_login");
}
获取授权 key :
Future<bool> isUserLogin() async{
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getString("auth_token");
}
注销方法
Future<void> logout() async{
SharedPreferences pref = await SharedPreferences.getInstance();
pref.remove("auth_key");
pref.remove("is_login");
}
我只是给你一个如何做的例子,你需要在下面的链接阅读更多关于“SharedPreferences”的内容来了解更多 还有另一种技术,比如将数据保存到 sql,但它更复杂,而且我猜它不太安全(因为有许多根应用程序作为 sqlite 浏览器工作)
关于authentication - 如何进行基本的 http 身份验证(登录和注册)并存储 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55320339/