Flutter LocalStorage:LateInitializationError:字段'localStorage'尚未初始化

Posted

技术标签:

【中文标题】Flutter LocalStorage:LateInitializationError:字段\'localStorage\'尚未初始化【英文标题】:Flutter LocalStorage: LateInitializationError: Field 'localStorage' has not been initializedFlutter LocalStorage:LateInitializationError:字段'localStorage'尚未初始化 【发布时间】:2021-08-03 06:52:22 【问题描述】:

我是 Flutter 的新手,我在使用 shared_preferences 为应用程序的自动登录功能时遇到了困难。 这是它的代码。

当异常被抛出时,这是堆栈:

#0 localStorage (package:ui_task/loginform.dart)

#1 MyApp.build (package:ui_task/main.dart:135:8)

#2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4706:28)

#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4632:15)

#4 Element.rebuild (package: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;
                    );
              

【问题讨论】:

堆栈跟踪中最顶层的条目是 #0 localStorage (package:ui_task/loginform.dart)。你能提供那个文件的代码吗? 当然我会编辑帖子。 【参考方案1】:

您在loginform.dart 文件的顶部定义localStorage,但您没有使用await SharedPreferences.getInstance(); 对其进行初始化,这就是引发错误的原因。除此之外,我不建议将密码以明文形式存储在shared_preferences 中(如果有的话)。它可以很容易地被提取出来。如果您绝对必须存储它,我建议:https://pub.dev/packages/flutter_secure_storage

【讨论】:

以上是关于Flutter LocalStorage:LateInitializationError:字段'localStorage'尚未初始化的主要内容,如果未能解决你的问题,请参考以下文章

Flutter入门Dart语言:简单易懂的变量指南

Flutter 里的语法糖解析,知其所然方能潇洒舞剑

在 2.7.0 之前的 sdk 版本中,是不是需要 Flutter 来保证 null 安全性?

如何访问 Flutter 的共享偏好文件?

Missing browser features DartPad requires localStorage to be enabled. For more information, Chrome

为 Flutter web 存储 JWT 令牌