Flutter LocalStorage: LateInitializationError: Field 'localStorage' has not been initialized
Flutter LocalStorage: LateInitializationError: Field 'localStorage' has not been initialized
我是 Flutter 的新手,在使用 shared_preferences 为应用程序提供自动登录功能时遇到了困难。
这是它的代码。
抛出异常时,这是堆栈:
#0 本地存储(包:ui_task/loginform.dart)
#1 MyApp.build(包:ui_task/main.dart:135:8)
#2 StatelessElement.build(包:flutter/src/widgets/framework.dart:4706:28)
#3 ComponentElement.performRebuild(包:flutter/src/widgets/framework.dart:4632:15)
#4 Element.rebuild(包:flutter/src/widgets/framework.dart:4322:5)
bool? isLoginDoneBefore;
void main() {
runApp(MyApp());
}
// ignore: must_be_immutable
class MyApp extends StatelessWidget {
// This widget is the root of your application.
// late bool? isLoginDoneBefore = localStorage.getBool("isLoginSuccessful");
@override
void initState() {
getData();
}
getData() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
isLoginDoneBefore=prefs.getBool("isLoginSuccessful");
}
Widget build(BuildContext context) {
// ignore: unnecessary_null_comparison
if(localStorage==null || isLoginDoneBefore==null){
return MaterialApp(
title: 'Login Form',
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
home: LoginFormWithAutoValidation(),
);
}
else {
return MaterialApp(
title: 'Login Form',
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
home: isLoginDoneBefore! ? afterLogin() : LoginFormWithAutoValidation(),
);
}
}
}
更新:添加最顶层的堆栈文件。
这是 loginform.dart:
late SharedPreferences localStorage;
class LoginFormWithAutoValidation extends StatefulWidget {
@override
_LoginFormWithAutoValidationState createState() => _LoginFormWithAutoValidationState();
// static Future init() async{
// localStorage = await SharedPreferences.getInstance();
// }
}
class _LoginFormWithAutoValidationState extends State<LoginFormWithAutoValidation> {
TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 20.0);
TextEditingController _passwordController = new TextEditingController();
TextEditingController _unameController = new TextEditingController();
final _formKey = new GlobalKey<FormState>();
late bool isLoginSuccessful;
late String? _uname;
late String? _password;
bool _autoValidate = false;
save() async{
// await LoginFormWithAutoValidation.init();
localStorage.setString('uname',_unameController.text.toString());
localStorage.setString('password',_passwordController.text.toString());
localStorage.setBool("isLoginSuccessful",true);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey[900],
body: Center(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
. . . . .
Material(
// login button
onPressed: () {
if (_formKey.currentState!.validate()) {
save();
Navigator.push(context,MaterialPageRoute(builder: (context) {
return afterLogin();}));
} else {
setState(()
// validation error
_autoValidate = true;
});
}
您在 loginform.dart
文件的顶部定义了 localStorage
,但您没有使用 await SharedPreferences.getInstance();
初始化它,这就是引发错误的原因。除此之外,我不建议将密码以明文形式存储在 shared_preferences
中(如果有的话)。它很容易被提取出来。如果您绝对必须存储它,我建议:https://pub.dev/packages/flutter_secure_storage
我是 Flutter 的新手,在使用 shared_preferences 为应用程序提供自动登录功能时遇到了困难。 这是它的代码。
抛出异常时,这是堆栈:
#0 本地存储(包:ui_task/loginform.dart)
#1 MyApp.build(包:ui_task/main.dart:135:8)
#2 StatelessElement.build(包:flutter/src/widgets/framework.dart:4706:28)
#3 ComponentElement.performRebuild(包:flutter/src/widgets/framework.dart:4632:15)
#4 Element.rebuild(包:flutter/src/widgets/framework.dart:4322:5)
bool? isLoginDoneBefore;
void main() {
runApp(MyApp());
}
// ignore: must_be_immutable
class MyApp extends StatelessWidget {
// This widget is the root of your application.
// late bool? isLoginDoneBefore = localStorage.getBool("isLoginSuccessful");
@override
void initState() {
getData();
}
getData() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
isLoginDoneBefore=prefs.getBool("isLoginSuccessful");
}
Widget build(BuildContext context) {
// ignore: unnecessary_null_comparison
if(localStorage==null || isLoginDoneBefore==null){
return MaterialApp(
title: 'Login Form',
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
home: LoginFormWithAutoValidation(),
);
}
else {
return MaterialApp(
title: 'Login Form',
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
home: isLoginDoneBefore! ? afterLogin() : LoginFormWithAutoValidation(),
);
}
}
}
更新:添加最顶层的堆栈文件。 这是 loginform.dart:
late SharedPreferences localStorage;
class LoginFormWithAutoValidation extends StatefulWidget {
@override
_LoginFormWithAutoValidationState createState() => _LoginFormWithAutoValidationState();
// static Future init() async{
// localStorage = await SharedPreferences.getInstance();
// }
}
class _LoginFormWithAutoValidationState extends State<LoginFormWithAutoValidation> {
TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 20.0);
TextEditingController _passwordController = new TextEditingController();
TextEditingController _unameController = new TextEditingController();
final _formKey = new GlobalKey<FormState>();
late bool isLoginSuccessful;
late String? _uname;
late String? _password;
bool _autoValidate = false;
save() async{
// await LoginFormWithAutoValidation.init();
localStorage.setString('uname',_unameController.text.toString());
localStorage.setString('password',_passwordController.text.toString());
localStorage.setBool("isLoginSuccessful",true);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey[900],
body: Center(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
. . . . .
Material(
// login button
onPressed: () {
if (_formKey.currentState!.validate()) {
save();
Navigator.push(context,MaterialPageRoute(builder: (context) {
return afterLogin();}));
} else {
setState(()
// validation error
_autoValidate = true;
});
}
您在 loginform.dart
文件的顶部定义了 localStorage
,但您没有使用 await SharedPreferences.getInstance();
初始化它,这就是引发错误的原因。除此之外,我不建议将密码以明文形式存储在 shared_preferences
中(如果有的话)。它很容易被提取出来。如果您绝对必须存储它,我建议:https://pub.dev/packages/flutter_secure_storage