Flutter 颤振本地存储:LateInitializationError:字段';本地存储';尚未初始化

Flutter 颤振本地存储:LateInitializationError:字段';本地存储';尚未初始化,flutter,sharedpreferences,Flutter,Sharedpreferences,我是一个新手,在使用应用程序自动登录功能的共享_首选项时,我被卡住了。 这是它的代码 引发异常时,这是堆栈: #0本地存储(包:ui\u task/loginform.dart) #1 MyApp.build(包:ui\u task/main.dart:135:8) #2.element.build(包:flatter/src/widgets/framework.dart:4706:28) #3 ComponentElement.performRebuild(包:flatter/src/widg

我是一个新手,在使用应用程序自动登录功能的共享_首选项时,我被卡住了。 这是它的代码

引发异常时,这是堆栈:

#0本地存储(包:ui\u task/loginform.dart)

#1 MyApp.build(包:ui\u task/main.dart:135:8)

#2.element.build(包:flatter/src/widgets/framework.dart:4706:28)

#3 ComponentElement.performRebuild(包:flatter/src/widgets/framework.dart:4632:15)

#4.Element.rebuild(包:flatter/src/widgets/framework.dart:4322:5)

更新:添加最顶层的堆栈文件。 这是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;
                    });
              }


延迟共享引用本地存储;
类LoginFormWithAutoValidation扩展了StatefulWidget{
@凌驾
_LoginFormWithAutoValidationState createState()=>\u LoginFormWithAutoValidationState();
//静态Future init()异步{
//localStorage=等待SharedReferences.getInstance();
// }
}
类_LoginFormWithAutoValidationState扩展状态{
TextStyle=TextStyle(fontFamily:'Montserrat',fontSize:20.0);
TextEditingController_passwordController=新的TextEditingController();
TextEditingController_unaconcontroller=新的TextEditingController();
final _formKey=新的GlobalKey();
晚期布尔岛成功;
晚字符串?\u uname;
延迟字符串?\u密码;
bool _autoValidate=false;
save()异步{
//等待LoginFormWithAutoValidation.init();
localStorage.setString('uname',_unameController.text.toString());
localStorage.setString('password',_passwordController.text.toString());
setBool(“isloginsucessful”,true);
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
背景颜色:颜色。蓝灰色[900],
正文:中(
子:SingleChildScrollView(
孩子:填充(
填充:常数边集全部(10.0),
子:列(
. . . . .
材料(
//登录按钮
已按下:(){
如果(_formKey.currentState!.validate()){
save();
Navigator.push(上下文,MaterialPage路由(生成器:(上下文){
返回afterLogin();});
}否则{
设置状态()
//验证错误
_自动验证=真;
});
}

您正在
loginform.dart
文件顶部定义
localStorage
,但您没有使用
wait SharedPreferences.getInstance();
初始化它,这就是引发错误的原因。除此之外,我不建议将密码以明文形式存储在
共享的\u首选项中(如果有的话)。它可以很容易地提取。如果你一定要存储它,我建议:

stacktrace中最上面的条目是this
\0 localStorage(package:ui\u task/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;
                    });
              }