flutter - 如何在 Flutter 应用中保存登录名和用户信息
问题描述
我想在登录后保存我的登录信息并将用户信息保存在模型中。
我该怎么做?我已遵循此文档,但它对我不起作用。
我想要它在 ios 和 android 中
这是我目前的代码:
我的登录页面:
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,
),
],
),
),
),
),
),
),
],
),
));
}
}
这是我的登录功能:
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/Login.dart';
import '../../Models/AuthResponse.dart';
import '../../Models/User.dart';
saveCurrentLogin(Map responseJson) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
var user;
if ((responseJson != null && !responseJson.isEmpty)) {
user = Login.fromJson(responseJson).login;
} else {
user = "";
}
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);
}
这些是我的模型:
授权响应模型
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 Login {
final String login;
final String password;
Login(this.login, this.password);
Login.fromJson(Map<String, dynamic> json)
: login = json['login'],
password = json['password'];
}
用户模型
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,
};
}
解决方案
您能否提供更多详细信息,说明您的应用程序的哪个部分存在问题以及您收到了哪些错误?
至于您关于存储登录名或用户信息的问题,您可以选择很多方法。成功验证后,您可以将数据存储在Firebase Cloud Firestore或Realtime Database等数据库中。这真的取决于你的用例。
推荐阅读
- python - 如何告诉 beanstalkc 接收器在保留任务之前等待 X 秒?
- javascript - 单击按钮时,如何更改另一个页面中元素的类属性?
- corda - Corda - 在同一事务中具有多个状态的流中的性能
- logging - MarkLogic 8 - 请求没有超时 - 在记录 XDMP-XDQPNOSESSION 后不断重试
- javascript - 如何在 EJS 中使用三元运算符
- android - 从什么时候android在崩溃后重新启动应用程序?
- php - MySQL 在 DB Array 字段中查找数组值
- flutter - flutter_local_notifications 事件不起作用
- angular - 从服务器加载数据时的角度组件空白几秒钟
- reactjs - 在无限循环中动态添加和删除 className