我正在尝试确定登录后存储和访问 Flutter 应用程序的 User 对象的最佳方式。目前还没有真正的身份验证。因此,当“用户”登录时,它只是检查 json 文件中的虚拟用户名和密码。我唯一想知道的是从应用程序中的任何位置存储和访问我的用户 ID 的适当方法是什么?每次屏幕改变时我都会将它作为路由参数传递,但这似乎有点矫枉过正。最合适的方法是什么?只需创建一个 globals.dart 文件并将用户 ID 添加为变量即可?
json 格式的用户示例:
{
"id" : 5,
"fName" : "John",
"lName" : "Doe",
"position" : "Software Developer",
"username" : "jdoe",
"password" : "jdoepass",
"imageUrl": "assets/images/profile_pictures/profilePicture.png",
"email" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a606e656f4a65646f7a6b787e646f7824696567" rel="noreferrer noopener nofollow">[email protected]</a>",
"location" : "Big Software Company"
}
登录.dart:
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../utils/opWidgets.dart';
import '../utils/fetchJson.dart';
import '../../entities/User.dart';
/* Description: Login screen widget and functions to handle fetching user json */
class LoginPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _LoginPageState();
}
}
class _LoginPageState extends State<LoginPage> {
List<User> _userList = []; //used to represent the list items in the UI
final userTxtController = TextEditingController();
final passTxtController = TextEditingController();
User _currentUser;
bool _invalidUserMsgVisible = false;
@override
initState() {
//initializes data before build() is called
//Use this method to initialize data that will be displayed
//initialize list items using function that fetches/converts json
fetchUsers().then((value) {
setState(() {
_userList.addAll(value);
});
});
super.initState();
}
@override
void dispose() {
//releases memory
userTxtController.dispose();
passTxtController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: GestureDetector(
//Makes the keyboard collapse when the scaffold body is tapped
onTap: () => FocusScope.of(context).unfocus(),
child: _layoutDetails(),
),
);
}
//This widget determines the layout of the widgets _logo() and _loginForm() based on the screen's orientation
Widget _layoutDetails() {
Orientation orientation = MediaQuery.of(context).orientation;
if (orientation == Orientation.portrait) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_logo(),
_loginForm(),
],
);
} else {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_logo(),
Container(
width: MediaQuery.of(context).size.width / 1.8,
height: MediaQuery.of(context).size.height,
child: _loginForm(),
),
],
);
}
}
Widget _logo() {
return Container(
width: 225,
child: Image.asset('assets/images/logos/OPNewLogo.png'),
);
}
Widget _loginForm() {
return Container(
width: double.infinity,
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Visibility(
visible: _invalidUserMsgVisible,
child: Text(
'Username or password is invalid',
style: GoogleFonts.montserrat(color: Colors.red, fontSize: 14),
),
),
SizedBox(height: 5),
Container(
//margin: EdgeInsets.symmetric(horizontal: 10),
width: 500,
child: opTextField('Username', false, userTxtController),
),
SizedBox(height: 20),
Container(
//margin: EdgeInsets.symmetric(horizontal: 10),
width: 500,
child: opTextField('Password', true, passTxtController),
),
SizedBox(height: 20),
Container(
width: 500,
height: 40,
padding: EdgeInsets.symmetric(horizontal: 8),
child: ElevatedButton(
onPressed: () => _verifyLogin(
userTxtController.text.toString().trim(),
passTxtController.text.toString(),
),
child: Text(
'LOGIN',
style: GoogleFonts.montserrat(
fontSize: 16,
letterSpacing: 1.5,
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
primary: Theme.of(context).accentColor,
elevation: 3,
),
),
),
SizedBox(height: 5),
Container(
width: 500,
height: 40,
padding: EdgeInsets.symmetric(horizontal: 8),
child: ElevatedButton(
onPressed: () => {
Navigator.pop(context),
},
child: Text(
'REGISTER',
style: TextStyle(
fontSize: 16,
letterSpacing: 2.2,
color: Theme.of(context).shadowColor,
fontWeight: FontWeight.w500),
),
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: BorderSide(
color: Theme.of(context).primaryColorDark,
),
),
primary: Colors.white,
),
),
),
Container(
child: TextButton(
autofocus: false,
clipBehavior: Clip.none,
child: Text(
'Forgot Password',
style: GoogleFonts.montserrat(
fontSize: 15,
color: Theme.of(context).shadowColor,
decoration: TextDecoration.underline,
),
),
onPressed: () =>
Navigator.pushNamed(context, resetPasswordPageRoute),
),
),
],
),
);
}
//Function to check the username and password input against the list of user objects
void _verifyLogin(String username, String password) {
bool _validUser = false;
//Loop through fetched user objects and check for a match
for (var user in _userList) {
if (username == user.username && password == user.password) {
_validUser = true;
_currentUser = user; //Set the current user object
break;
}
}
//If a valid user was found, pop login screen and push home screen
if (_validUser) {
Navigator.popAndPushNamed(
context,
homePageRoute,
arguments:
_currentUser, //Pass the current user object to the home screen
);
} else {
//if no valid user was found, make error message text visible
setState(() {
_invalidUserMsgVisible = true;
});
}
}
}
最佳答案
您可以使用静态和类在整个应用程序中保存此数据
class SaveData{
static int id
setId(int id1){
id = id1;
}
getId(){
return id;
}
}
关于flutter - 从 Flutter 应用程序中的任何位置登录和访问后如何存储用户 ID 或 "key"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66871930/